Objective:
Vue originally had an official recommended Ajax plugin Vue-resource, but since Vue update to 2.0, Yu Yuxi announced the stop update Vue-resource, and recommended the use of Axios, more and more Vue projects, have chosen Axios to complete the AJ Ax request, and large projects use VUEX to manage data
Previously used is the Vue-resource plug-in, after the main import file introduced import Vueresource from ' Vue-resource ', directly after the use of Vue.use (Vueresource) can be a global reference to the plug-in;
When the first use of Axios, without the brain in accordance with the steps above the global reference, the result was miserable.
Looking at the document, Axios is a promise based HTTP library
Axios does not have a install method, so it is not possible to use the Vue.use () method.
So does every file have to be referenced once. There are many ways to solve this problem:
1. Combined with Vue-axios
2. Axios rewrite as Vue's prototype properties
3. Combine the Vuex action combined with Vue-axios use
Read the source code of Vue-axios, it is in accordance with the way Vue Plug-ins to write. Then combine the Vue-axios, you can use the Vue.use method
First, reference in the main entry file Main.js
Import Axios from ' Axios '
import vueaxios from ' Vue-axios '
vue.use (Vueaxios,axios);
You can then use the methods in the component file to use the
Getnewslist () {
this.axios.get (' api/getnewslist '). Then ((response) =>{
this.newslist= Response.data.data
}). catch ((response) =>{
Console.log (response);
})
},
Axios rewrite as Vue's prototype properties
First referenced in the main entry file Main.js, then hung on the prototype chain of Vue
Import Axios from ' Axios '
vue.prototype. $ajax = Axios
Using in Components
this. $ajax. Get (' api/getnewslist '). Then ((response) =>{
this.newslist=response.data.data;
}). catch ((response) =>{
Console.log (response);
})
Combining the Vuex action
Referenced in the Vuex warehouse file Store.js, using the action Add method
Import Vue from ' Vue '
import Vuex to ' Vuex '
import axios from ' Axios ' Vue.use
(VUEX)
Const STORE = new Vu Ex. Store ({
//definition State
: {
User: {
name: ' Xiaoming '
}
},
actions: {
//encapsulation of an Ajax method
Login (context) {
Axios ({method
: ' Post ',
URL: '/user ',
data:context.state.user
})
}
}
})
Export Default Store
When you send a request in an assembly, you need to use this. $store. Dispatch
Methods: {
SubmitForm () {this
. $store. Dispatch (' login ')
}
}