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')
  }
}
posted @ 2019-12-03 14:09  zhouwenfan  阅读(3458)  评论(0编辑  收藏  举报