在vue2.0中已经停止了对vue-resource的更新,并推荐使用axios库。
但不同于vue-resource插件,axios是一个基于promise的HTTP库,并不能通过import后Vue.use()的方式全局使用。
以下总结了三种全局使用axios的方法:
1、插件化:使用vue-axios
首先npm安装axios和vue-axios,然后在main.js入口文件引入
import axios from 'axios'
import VueAxios from 'vue-axios'
引入后就可以在methods中使用了
getNewsList(){
this.axios.get('api/getNewsList').then((response)=>{
this.newsList=response.data.data;
}).catch((response)=>{
console.log(response);
})
}
2、挂载到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);
})
3、结合Vuex的action
在vuex的仓库文件store.js中引用,使用action添加方法
import Vue from 'Vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
const store = new Vuex.Store({
// 定义状态
state: {
user: {
name: 'xiaoming'
}
},
actions: {
// 封装一个 ajax 方法
login (context) {
axios({
method: 'post',
url: '/user',
data: context.state.user
})
}
}
})
export default store
在组件中发送请求的时候,需要使用 this.$store.dispatch
methods: {
submitForm () {
this.$store.dispatch('login')
}
}
TIPS:
axios 的定位是 HTTP 工具库,在设计上是作为前后端数据交互的接口层。是和业务无关的,不应该使用 this 和组件关联。应该抽象 API 层出来,在 API 层里面使用 axios 就够了,没必要污染原型。
在多人协作的项目上应该抽象出API层,在业务组件中进行统一调用。添加到原型上以及使用vue.use()安装插件的方式使用,虽然减少了代码,但从工程化的角度来看,看似简洁,实则混乱。