This article brings you the content is about Vue based on the Vuex and Axios interceptors to achieve loading effect and Axios installation configuration, there is a certain reference value, the need for friends can refer to, I hope to help you.
Get ready
Creating Projects with VUE-CLI scaffolding
Enter Project installation Vuex, Axios (npm install vuex,npm install Axios)
Axios Configuration
After the installation of the Axios module (NPM install Axios) in the project, the following configuration is done:
Main.js
Introduce Axiosimport Axios from ' Axios '//Modify the prototype chain, using Axios globally, so that the methods command can be called $axios in each component's Vue.prototype to complete the data request. $axios =axios
Loading components
I choose to use the loading component provided by iview,
NPM install Iviewmain.jsimport iView from ' IView '; import ' iview/dist/styles/iview.css '; Vue.use (IView);
After the installation is introduced, loading is written as a component Loading.vue
Vuex State Setting control loading
Store.js (Vuex)
Export Const STORE = new Vuex.store ({ state:{ isshow:false }})
Define the Isshow property in state, default false to hide
V-if= "this. $store. State.isshow"
Adding v-if bindings to the loading component in the State isshow
Component requests data using Axios
<button @click = "GetData" > Request data </button>
methods:{ GetData () {this . $axios. Get (' Https://www.apiopen.top/journalismApi ') . Then (res=>{ Console.log (RES)//Returns the result of the request }) . catch (err=>{ console.log (err) })} }
I use a button here to trigger the event, using GET request on the Internet to find an API interface,. Then returns the entire result of the request (not just the data)
Axios Interceptor Configuration
Main.js
Define a request Interceptor Axios.interceptors.request.use (Function (config) { store.state.isshow=true;//do something before the request is issued return config})//Define a response interceptor Axios.interceptors.response.use (function (config) { store.state.isshow=false;// The returned data is processed here in return config})
Define a request interceptor (to perform certain actions at the beginning of a request), respond to interceptors (take certain actions after receiving data), set the actions to be performed separately, and change the Boolean value of Isshow within the state to control the loading component display at the start of the triggering request data loading , hide loading when returning data
Special Note : Here's a syntax pit (I've been stepping back and forth a lot of times) Main.js, manipulating the data in Vuex state differs from this in the component. $store. State, but directly store.state with the above code
Effect Show