使用vuex在vue + vant 项目中加 loading加载

由于项目需要,参考网上例子,自己动手写了一个,废话不多说,上代码。

在src目录下新建store目录,store目录下新建store.js文件  (已确保已装好vuex)

import Vue from 'vue'
import Vuex from 'vuex';
 
Vue.use(Vuex);
 
const store = new Vuex.Store({
    state: {
        LOADING: false
    },
    mutations: {
        showLoading(state){
            state.LOADING = true    
        },
        hideLoading (state) {
            state.LOADING = false
        }
    }
})
export default store
 

loading组件如下:(图片建议网上找无背景的图)


 

在app.vue中使用loading组件


 

 

然后main.js

import store from './store/store'
 
Vue.use(moment);
Vue.use(Vant)
Vue.config.productionTip = false
 
 
new Vue({
  render: h => h(App),
  router,
  store
}).$mount('#app')

如果需要在请求封装中使用在请求中加

axios.interceptors.request.use(
    config => {
        store.commit('showLoading')
    error => {
        store.commit('hideLoading')
    })
axios.interceptors.response.use(
    response => {
        store.commit('hideLoading')
    },
 
    error => {
        store.commit('hideLoading')
    }
);

如在单个请求中使用,在 请求时 中加\

this.$store.commit('showLoading')
       
   请求完成后加    
this.$store.commit('hideLoading')

感谢分享https://blog.csdn.net/qq_36247432/article/details/83054140

你可能感兴趣的:(vue,vuex)