在vue項目開發中,我們使用axios進行ajax請求,很多人一開始使用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中引用:
1
2
3
4
|
import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios,axios); |
之后就可以使用了,在組件文件中的methods里去使用了:
1
2
3
4
5
6
7
|
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
在組件中使用:
1
2
3
4
5
6
|
this .$ajax.get( 'api/getNewsList' ) .then((response)=>{ this .newsList=response.data.data; }). catch ((response)=>{ console.log(response); }) |
結合 Vuex的action
在vuex的倉庫文件store.js中引用,使用action添加方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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
1
2
3
4
5
|
methods: { submitForm () { this .$store.dispatch( 'login' ) } } |
補充知識:ElementUI 在VUE中配置 main.js與axios的關系
一、在main.js中:
import ElementUI from 'element-ui'
Vue.use(ElementUI)
二、在main.js中,數據請求axios不能在這里配置
以上這篇vue全局使用axios的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000013128858