vue2.0 Axios 的简单用法

vue

安装


 使用 npm:

$ npm install axios

使用 bower:

$ bower install axios

使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

用法


 在main.js文件中,配置axios

//引入axios

import Axios from 'axios';

//将 axios 改写为 Vue 的原型属性

Vue.prototype.$axios = Axios;

在 main.js 中添加了这两行代码之后,就可以直接在组件的 created 钩子中使用 $axios 命令

created() {

this.$axios.post('https://www.easy-mock.com/mock/5b23687cf3c9fb2931a37f69/example')

.then(res => {

console.log(res.data);

})

.catch(error => {

console.log(error);

})

}

拦截器


在请求或响应被 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);

});

以上是 vue2.0 Axios 的简单用法 的全部内容, 来源链接: utcz.com/z/380915.html

回到顶部