vue全局使用axios的方法汇总
在vue项目开发中,我们使用axios进行ajax请求,很多人一开始使用axios的方式,会当成vue-resoure的使用方式来用,即在主入口文件引入import VueResource from ‘vue-resource’之后,直接使用Vue.use(VueResource)之后即可将该插件全局引用了,所以axios这样使用的时候就报错了,很懵逼。
仔细看看文档,就知道axios 是一个基于 promise 的 HTTP 库,axios并没有install 方法,所以是不能使用vue.use()方法
那么难道我们要在每个文件都要来引用一次axios吗?
其实解决方案有两种:
1.结合 vue-axios使用
2.axios 改写为 Vue 的原型属性
1.结合 vue-axios使用
看了vue-axios的源码,它是按照vue插件的方式去写的。那么结合vue-axios,就可以去使用vue.use方法了
首先在主入口文件main.js中引用:
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios);
# 在组件中使用:
getNewsList(){
this.axios.get('api/getNewsList').then((response)=>{
this.newsList=response.data.data;
}).catch((response)=>{
console.log(response);
})
}
2.axios 改写为 Vue 的原型属性
首先在主入口文件main.js中引用,之后挂在vue的原型链上:
import axios from 'axios'
Vue.prototype.$ajax= axios
# 在组件中使用:
this.$ajax.get('api/getNewsList')
.then((response)=>{
this.newsList=response.data.data;
}).catch((response)=>{
console.log(response);
})