1. 程式人生 > 程式設計 >vue全域性使用axios的操作

vue全域性使用axios的操作

在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中引用:

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')
 }
}

補充知識:ElementUI 在VUE中配置 main.js與axios的關係

一、在main.js中:

import ElementUI from 'element-ui'

Vue.use(ElementUI)

二、在main.js中,資料請求axios不能在這裡配置

以上這篇vue全域性使用axios的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。