Vue全局使用axios的方法

axios 是一个基于 promiseHTTP 库,axios并没有install方法,所以是不能使用vue.use()方法的。

1. 结合vue-axios使用

看了[vue-axios](https://www.npmjs.com/package/vue-axios)的源码说明,它是按照vue插件的方式去写的。那么结合vue-axios,就可以去使用vue.use()方法了。

安装:

npm install axios vue-axios --save

main.js引用

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

项目组件上面使用

Vue.axios.get(api).then((response) => {
  console.log(response.data)
}).catch((err)=>{
  console.log(err.data);
})
 
this.axios.get(api).then((response) => {
  console.log(response.data)
}).catch((err)=>{
  console.log(err.data);
})
 
this.$http.get(api).then((response) => {
  console.log(response.data)
}).catch((err)=>{
  console.log(err.data);
})

2. axios 改写为 Vue 的原型属性

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

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

使用:

this.$http.get('api')
.then((response)=>{
    console.log(response.data)
}).catch((err)=>{
    console.log(err);
})

3.结合 Vuexaction

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: 'root'
    }
  },
  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')
  }
}

你可能感兴趣的:(vue)