在vue項目開發中,我們使用axios的二次封裝,很多人一開始使用axios的方式,會當成vue-resoure的使用方式來用,即在主入口文件引入import VueResource from 'vue-resource'之后,直接使用Vue.use(VueResource)之后即可將該插件全局引用了,所以axios這樣使用的時候就報錯了,很懵逼。
仔細看看文檔,就知道axios 是一個基於 promise 的 HTTP 庫,axios並沒有install 方法,所以是不能使用vue.use()方法的。☞查看vue插件
那么難道我們要在每個文件都要來引用一次axios嗎?多繁瑣!!!解決方法有很多種:
1.結合 vue-axios使用
2.axios 改寫為 Vue 的原型屬性
3.結合 Vuex的action
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);
之后就可以使用了,在組件文件中的methods里去使用了:
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);
})
結合 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')
}
}
