vue学习过程总结(04)-菜鸟教程归纳
1.组件
组件(component)是vue.js最强⼤的功能之⼀。组件可以扩展html元素,封装可重⽤的代码。组件系统让我们可以⽤独⽴可复⽤的⼩组件来构建⼤型应⽤,⼏乎任意类型的应⽤的界⾯都可以抽象为⼀个组件树。
  1.1.注册⼀个全局组件:
Vueponent(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>
Vueponent('button-counter', {
template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
incrementHandler: function () {
this.$emit('increment')
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
}
}
})
</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库:
中⽂⽂档地址:
<router-link> 是⼀个组件,该组件⽤于设置⼀个导航链接,切换不同 HTML 内容。 to 属性为⽬标地址,即要显⽰的内容。
<router-link> 相关属性有:to/replace/appead(相当于router.push()/ place()/ router.appead())  tag/active-class/exact-active-class/event
5.axios
  5.1.Axios 是⼀个基于 Promise 的 HTTP 库,可以⽤在浏览器和 node.js 中。Github开源地址:
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get('www.runoob/try/ajax/json_demo.json')
.then(response => (this.info = response))
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
})
mounted,method,computed三者的区别:(转载 www.jianshu/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('www.runoob/try/ajax/json_demo.json')
.then(response => (this.info = response))
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
})
//NO.3. 直接在 URL 上添加参数 ID=12345
<('/user?ID=12345')
.
then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// NO.4.也可以通过 params 设置参数:
<('/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('www.runoob/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: "some-domain/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. www.npmjs/package/qs, api.jquery/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 。如果 `validateStat
us` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte  validateStatus: function (status) {
return status >= 200 && status < 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 = 'ample';
axios.defaults.headersmon['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 处理前拦截它们。
// 添加请求
quest.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
ject(error);
});
// 添加响应
sponse.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
ject(error);
});
  6.2.移除。
#method1.
var myInterceptor = quest.use(function () {/*...*/});
quest.eject(myInterceptor);
  6.3.⾃定义 axios 实例添加。
#method2.⾃定义 axios 实例添加。
var instance = ate();
quest.use(function () {/*...*/});
  6.4.使⽤ cancel token 取消请求。
# mthod1.使⽤ CancelToken.source ⼯⼚⽅法创建 cancel token
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
<('/user/12345', {
cancelToken: ken
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', ssage);
} else {
// 处理错误
}
});
// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');
# mthod2.可以通过传递⼀个 executor 函数到 CancelToken 的构造函数来创建 cancel token:var CancelToken = axios.CancelToken;
var cancel;
<('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函数接收⼀个 cancel 函数作为参数
cancel = c;
})
});
jquery学习在线教程// 取消请求
cancel();
  请求头配置:
headers: { 'content-type': 'application/x-www-form-urlencoded' },

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。