在vue項目開發(fā)中鞋诗,我們使用axios進行ajax請求衷畦,很多人一開始使用axios的方式懊亡,會當(dāng)成vue-resoure的使用方式來用署驻,即在主入口文件引入import VueResource from 'vue-resource'之后瞧掺,直接使用Vue.use(VueResource)之后即可將該插件全局引用了耕餐,所以axios這樣使用的時候就報錯了,很懵逼辟狈。
仔細看看文檔肠缔,就知道axios 是一個基于 promise 的 HTTP 庫,axios并沒有install 方法哼转,所以是不能使用vue.use()方法的明未。?查看vue插件
那么難道我們要在每個文件都要來引用一次axios嗎?多繁瑣R悸Q怯纭!解決方法有很多種:
1.結(jié)合 vue-axios使用
2.axios 改寫為 Vue 的原型屬性
3.結(jié)合 Vuex的action
1.結(jié)合 vue-axios使用
看了vue-axios的源碼庶溶,它是按照vue插件的方式去寫的煮纵。那么結(jié)合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);
})
結(jié)合 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({
// 定義狀態(tài)
state: {
user: {
name: 'xiaoming'
}
},
actions: {
// 封裝一個 ajax 方法
login (context) {
axios({
method: 'post',
url: '/user',
data: context.state.user
})
}
}
})
export default store
在組件中發(fā)送請求的時候,需要使用 this.$store.dispatch
methods: {
submitForm () {
this.$store.dispatch('login')
}
}