vue全局使用axios的方法

在vue項目開發中,咱們使用axios進行ajax請求,不少人一開始使用axios的方式,會當成vue-resoure的使用方式來用,即在主入口文件引入import VueResource from 'vue-resource'以後,直接使用Vue.use(VueResource)以後便可將該插件全局引用了,因此axios這樣使用的時候就報錯了,很懵逼。html

仔細看看文檔,就知道axios 是一個基於 promise 的 HTTP 庫,axios並無install 方法,因此是不能使用vue.use()方法的。☞查看vue插件
那麼難道咱們要在每一個文件都要來引用一次axios嗎?多繁瑣!!!解決方法有不少種:
1.結合 vue-axios使用
2.axios 改寫爲 Vue 的原型屬性
3.結合 Vuex的actionvue

1.結合 vue-axios使用

看了vue-axios的源碼,它是按照vue插件的方式去寫的。那麼結合vue-axios,就能夠去使用vue.use方法了ios

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

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios);

以後就能夠使用了,在組件文件中的methods裏去使用了:vuex

getNewsList(){
      this.axios.get('api/getNewsList').then((response)=>{
        this.newsList=response.data.data;
      }).catch((response)=>{
        console.log(response);
      })
}

2.axios 改寫爲 Vue 的原型屬性(不推薦這樣用)

首先在主入口文件main.js中引用,以後掛在vue的原型鏈上:npm

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

在組件中使用:axios

this.$ajax.get('api/getNewsList')
.then((response)=>{
    this.newsList=response.data.data;
}).catch((response)=>{
    console.log(response);
})

結合 Vuex的action
在vuex的倉庫文件store.js中引用,使用action添加方法api

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.dispatchpromise

methods: {
  submitForm () {
    this.$store.dispatch('login')
  }
}
相關文章
相關標籤/搜索