The content of this article is about Vue’s loading effect based on vuex and axios interceptor and the installation configuration of axios. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
Preparation
Use vue-cli scaffolding to create a project
Enter the project to install vuex and axios (npm install vuex,npm install axios)
axios configuration
Install in the project After the axios module (npm install axios) is completed, perform the following configuration:
main.js
//引入axios import Axios from 'axios' //修改原型链,全局使用axios,这样之后可在每个组件的methods中调用$axios命令完成数据请求 Vue.prototype.$axios=Axios
loading component
I choose to use the loading component provided by iview here.
npm install iview main.js import iView from 'iview'; import 'iview/dist/styles/iview.css'; Vue.use(iView);
After installation and introduction, write loading as a component loading.vue
Vuex state setting controls the visibility of loading
##store.js(Vuex)
export const store = new Vuex.Store({ state:{ isShow:false } })
v-if="this.$store.state.isShow"
The component uses axios to request data
<button>请求数据</button>
methods:{ getData(){ this.$axios.get('https://www.apiopen.top/journalismApi') .then(res=>{ console.log(res)//返回请求的结果 }) .catch(err=>{ console.log(err) }) } }
Axios interceptor configuration
main.js
//定义一个请求拦截器 Axios.interceptors.request.use(function(config){ store.state.isShow=true; //在请求发出之前进行一些操作 return config }) //定义一个响应拦截器 Axios.interceptors.response.use(function(config){ store.state.isShow=false;//在这里对返回的数据进行处理 return config })
Special attention: There is a syntax pit here (I stepped on it many times). The data in main.js that is called and manipulated in vuex state is different from this.$store.state in the component, but directly store.state Same as the above code
Effect display
Vue configuration axios method step example
Implement animation switching function based on Vue, Vuex, and Vue-router
The above is the detailed content of Vue implements loading effects and axios installation configuration based on vuex and axios. For more information, please follow other related articles on the PHP Chinese website!