溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue項(xiàng)目全局如何使用axios

發(fā)布時間:2020-10-24 15:37:38 來源:億速云 閱讀:253 作者:小新 欄目:web開發(fā)

這篇文章主要介紹了vue項(xiàng)目全局如何使用axios,具有一定借鑒價(jià)值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。

共有三種方法:

1.結(jié)合 vue-axios使用

首先在主入口文件main.js中引用

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios);

之后就可以在組件文件中的methods里去使用了

this.axios.get('/api/usrmng')
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

2. axios 改寫為 Vue 的原型屬性

首先在主入口文件main.js中引用,之后掛在vue的原型鏈上

import axios from 'axios'
Vue.prototype.$http = axios

在組件中使用

this.$http.get('/api/usrmng')
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

3.結(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: 'root'
    }
  },
  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')
  }
}

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享vue項(xiàng)目全局如何使用axios內(nèi)容對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,遇到問題就找億速云,詳細(xì)的解決方法等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI