本篇文章給大家分享的是有關如何在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);
})
}首先在主入口文件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的倉庫文件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')
}
}以上就是如何在vue中全局使用axios,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。