1.组件

组件(component)是vue.js最强大的功能之一。组件可以扩展html元素,封装可重用的代码。组件系统让我们可以用独立可复用的小组件来构建大型应用,几乎任意类型的应用的界面都可以抽象为一个组件树。

  1.1.注册一个全局组件:

Vue.component(tagName, options)

tagName 为组件名,options 为配置选项。注册后,我们可以使用以下方式来调用组件:<tagName></tagName>

prop 是父组件用来传递数据的一个自定义属性。

2.事件

  2.1.使用.native监听组件上原生事件。如:

<my-component v-on:click.native="doTheThing"></my-component>

  2.2.监听事件:$on(eventName);触发父组件的自定义事件:$emit( event, arg )

<div id="app">
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
</div> <script>
Vue.component('button-counter', {
template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
incrementHandler: function () {
this.counter += 1
this.$emit('increment')
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})
</script>

子组件将counter加1后调用的父组件的increment点击事件,进行两个total加1的计算。

{}用于定义对象,如:var obj = {"id":"12","name":"jack"}.  []用于声明函数,如:var a = [1,"ad"]

例子中的data是一个函数,好处是每个实例可以维护一份被返回对象的独立的拷贝,如果 data 是一个对象则会影响到其他实例。

3.自定义指令

除了默认设置的核心指令( v-model 和 v-show ), Vue 也允许注册自定义指令。定义全局指令:directive  定义局部指令:directives

下面我们注册一个全局指令 v-focus, 该指令的功能是在页面加载时,元素获得焦点:

<div id="app">
<p>页面载入时,input 元素自动获取焦点:</p>
<input v-focus>
</div> <script>
// 注册一个全局自定义指令 v-focus
Vue.directive('focus', {
// 当绑定元素插入到 DOM 中。
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
// 创建根实例
new Vue({
el: '#app'
})
</script>

指令定义函数提供了几个钩子函数,函数有:bind/inserted/update/componentUpdated/unbind.

钩子函数的参数有el/binding/vnode/oldVnode;其中binding是一个对象有这些属性name/value/oldValue/expression/arg/modifiers

4.路由

通过vue.js的路由可以通过不同的url访问不同的内容,vue.js路由需要载入vue-router库:https://github.com/vuejs/vue-router

中文文档地址:https://router.vuejs.org/zh/

<router-link> 是一个组件,该组件用于设置一个导航链接,切换不同 HTML 内容。 to 属性为目标地址, 即要显示的内容。

<router-link> 相关属性有:to/replace/appead(相当于router.push()/ router.replace()/ router.appead())  tag/active-class/exact-active-class/event

5.axios

  5.1.Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中。Github开源地址: https://github.com/axios/axios

new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get('https://www.runoob.com/try/ajax/json_demo.json')
.then(response => (this.info = response))
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
})

mounted,method,computed三者的区别:(转载 https://www.jianshu.com/p/c5b1dd18eda2)

mounted : 在这发起后端请求,拿回数据,配合路由钩子做一些事情 (dom渲染完成 组件挂载完成 )methods中一般都是定义的需要事件触发的一些函数。每次只要触发事件,就会执行对应的方法。如果把computed中的方法写到method中会浪费性能。computed必须返回一个值页面绑定的才能取得值,而methods中可以只执行逻辑代码,可以有返回值,也可以没有。

axios请求的几种写法:

axios(config)
//NO.1. 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}); //NO.2. 发送 GET 请求
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get('https://www.runoob.com/try/ajax/json_demo.json')
.then(response => (this.info = response))
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
}) //NO.3. 直接在 URL 上添加参数 ID=12345
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
}); // NO.4.也可以通过 params 设置参数:
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
}); // NO.5.
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.post('https://www.runoob.com/try/ajax/demo_axios_post.php')
.then(response => (this.info = response))
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
}) // NO.6.
axios.post('/user', {
firstName: 'Fred', // 参数 firstName
lastName: 'Flintstone' // 参数 lastName
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

  5.2.请求配置项。下面是创建请求时可用的配置选项,注意只有 url 是必需的。如果没有指定 method,请求将默认使用 get 方法。

注意这是局部的请求的完整写法,与5.1比较。

{
// `url` 是用于请求的服务器 URL
url: "/user", // `method` 是创建请求时使用的方法
method: "get", // 默认是 get // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: "https://some-domain.com/api/", // `transformRequest` 允许在向服务器发送前,修改请求数据
// 只能用在 "PUT", "POST" 和 "PATCH" 这几个请求方法
// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data) {
// 对 data 进行任意转换处理 return data;
}], // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对 data 进行任意转换处理 return data;
}], // `headers` 是即将被发送的自定义请求头
headers: {"X-Requested-With": "XMLHttpRequest"}, // `params` 是即将与请求一起发送的 URL 参数
// 必须是一个无格式对象(plain object)或 URLSearchParams 对象
params: {
ID: 12345
}, // `paramsSerializer` 是一个负责 `params` 序列化的函数
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: "brackets"})
}, // `data` 是作为请求主体被发送的数据
// 只适用于这些请求方法 "PUT", "POST", 和 "PATCH"
// 在没有设置 `transformRequest` 时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属:FormData, File, Blob
// - Node 专属: Stream
data: {
firstName: "Fred"
}, // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
// 如果请求花费了超过 `timeout` 的时间,请求将被中断
timeout: 1000, // `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // 默认的 // `adapter` 允许自定义处理请求,以使测试更轻松
// 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
adapter: function (config) {
/* ... */
}, // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
// 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
auth: {
username: "janedoe",
password: "s00pers3cret"
}, // `responseType` 表示服务器响应的数据类型,可以是 "arraybuffer", "blob", "document", "json", "text", "stream"
responseType: "json", // 默认的 // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
xsrfCookieName: "XSRF-TOKEN", // default // `xsrfHeaderName` 是承载 xsrf token 的值的 HTTP 头的名称
xsrfHeaderName: "X-XSRF-TOKEN", // 默认的 // `onUploadProgress` 允许为上传处理进度事件
onUploadProgress: function (progressEvent) {
// 对原生进度事件的处理
}, // `onDownloadProgress` 允许为下载处理进度事件
onDownloadProgress: function (progressEvent) {
// 对原生进度事件的处理
}, // `maxContentLength` 定义允许的响应内容的最大尺寸
maxContentLength: 2000, // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
validateStatus: function (status) {
return status &gt;= 200 &amp;&amp; status &lt; 300; // 默认的
}, // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
// 如果设置为0,将不会 follow 任何重定向
maxRedirects: 5, // 默认的 // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
// `keepAlive` 默认没有启用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }), // "proxy" 定义代理服务器的主机名称和端口
// `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
// 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
proxy: {
host: "127.0.0.1",
port: 9000,
auth: : {
username: "mikeymike",
password: "rapunz3l"
}
}, // `cancelToken` 指定用于取消请求的 cancel token
// (查看后面的 Cancellation 这节了解更多)
cancelToken: new CancelToken(function (cancel) {
})
}

响应结构:

{
// `data` 由服务器提供的响应
data: {}, // `status` HTTP 状态码
status: 200, // `statusText` 来自服务器响应的 HTTP 状态信息
statusText: "OK", // `headers` 服务器响应的头
headers: {}, // `config` 是为请求提供的配置信息
config: {}
}

  5.3.全局配置 axios的默认值。

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

  5.4.配置的优先顺序。

配置会以一个优先顺序进行合并。这个顺序是:在 lib/defaults.js 找到的库的默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后者将优先于前者。

6.拦截器。

  6.1.在请求或响应被 then 或 catch 处理前拦截它们。
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
}); // 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
  6.2.移除拦截器。
#method1.
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
  6.3.自定义 axios 实例添加拦截器。
#method2.自定义 axios 实例添加拦截器。
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
  6.4.使用 cancel token 取消请求。
# mthod1.使用 CancelToken.source 工厂方法创建 cancel token
var CancelToken = axios.CancelToken;
var source = CancelToken.source(); axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// 处理错误
}
}); // 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.'); # mthod2.可以通过传递一个 executor 函数到 CancelToken 的构造函数来创建 cancel token:
var CancelToken = axios.CancelToken;
var cancel; axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函数接收一个 cancel 函数作为参数
cancel = c;
})
}); // 取消请求
cancel();
  请求头配置:
headers: { 'content-type': 'application/x-www-form-urlencoded' },
 
 

最新文章

  1. Windows Form调用R进行绘图并显示
  2. Java编程思想重点笔记(Java开发必看)
  3. 通过底层AVR方法实现SPI数据传输
  4. 使用百度出品的 uaredirect.js 来判断客户端是否为手机
  5. 设计模式:状态模式(State)
  6. (转)jQuery轻量级响应式图片轮播插件ResponsiveSlides.js(仅1kb)也可以做纯文本轮播
  7. R cannot be resolved to a variable
  8. 鼠标滑轮一滚动Excel就停止工作
  9. drupal中使用jquery&amp;ajax
  10. Adapter基本用法
  11. ASP.NET没有魔法——ASP.NET MVC是如何运行的?它的生命周期是什么?
  12. thinkinginjava学习笔记07_多态
  13. Spring对象生存周期(Scope)的分析
  14. ios View 向上拉界面源码
  15. golang自动构建脚本
  16. [Swift]LeetCode482. 密钥格式化 | License Key Formatting
  17. Problem 9: Special Pythagorean triplet
  18. tp5参数绑定
  19. Vue(九)小案例 - 百度搜索列表(跨域)
  20. JS设计模式(1)单例模式

热门文章

  1. 系统基础优化( 创建yum私有仓库最详细操作及解释 )
  2. Solution -「NOI.AC 省选膜你赛」array
  3. 【职业规划】该如何选择职业方向?性能?自动化?测开?,学习选择python、java?看完你会感谢我的~
  4. etcd受损节点重新加入集群
  5. .NET CORE 鉴权
  6. Nginx兼容框架的pathinfo模式与URL重写
  7. Vue2.0源码学习(3) - 组件的创建和patch过程
  8. 一文带你解读Spring5源码解析 IOC之开启Bean的加载,以及FactoryBean和BeanFactory的区别。
  9. JwtAccessTokenConverter问题整理
  10. 了解MySQL存储引擎工作原理