vue Global Operation Using axios

  • 2021-08-12 01:49:41
  • OfStack

In the development of vue project, we use axios to request ajax. Many people start to use axios, which will be used as vue-resoure, that is, after the main entry file introduces import VueResource from 'vue-resource', the plug-in can be referenced globally after using Vue. use (VueResource) directly, so axios is used in this way.

A closer look at the documentation shows that axios is an HTTP library based on promise, and axios does not have install method, so vue. use () method cannot be used. View vue plug-in

So do we have to reference axios once in every file? How cumbersome! ! ! There are many solutions:

1. Use in conjunction with vue-axios

2. axios is rewritten as prototype attribute of Vue

3. action combined with Vuex

1. Use in conjunction with vue-axios

Read the vue-axios source code, it is in accordance with the vue plug-in to write. Then you can use the vue. use method in combination with vue-axios

First referenced in the main entry file main. js:


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

Vue.use(VueAxios,axios);

After that, you can use it in methods in the component file:


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

2. Rewrite axios to prototype attribute of Vue (not recommended)

It is first referenced in the main entry file main. js, and then hung on the prototype chain of vue:

import axios from 'axios'

Vue.prototype.$ajax= axios

Use in components:


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

action combined with Vuex

Referenced in the warehouse file store. js of vuex, using the action addition method


import Vue from 'Vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)
const store = new Vuex.Store({
 //  Definition status 
 state: {
  user: {
   name: 'xiaoming'
  }
 },
 actions: {
  //  Encapsulation 1 A  ajax  Method 
  login (context) {
   axios({
    method: 'post',
    url: '/user',
    data: context.state.user
   })
  }
 }
})

export default store

When sending a request in a component, you need to use this. $store. dispatch


methods: {
 submitForm () {
  this.$store.dispatch('login')
 }
}

Additional knowledge: ElementUI configures main in VUE. Relationship between js and axios

1. In main. js:

import ElementUI from 'element-ui'

Vue.use(ElementUI)

2. In main. js, data request axios cannot be configured here


Related articles: