vue項目通過vuex全局定義loading,簡單記錄一下
涉及的方面:elementUI(其中loading) 、vuex
引入vuex
//main.js
import store from './vuex/index';
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app');
在能正常使用elementUi和vuex前提下,直接記錄全局loading的步驟
1. App.vue
只保留有關loading的代碼
<template>
<div id="app"
v-loading="isShow"
element-loading-text="加載中"
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(0, 0, 0, 0.8)"
>
<router-view v-if="isRouterAlive"></router-view>
</div>
</template>
computed:{
isShow(){
return this.$store.getters.isLoadingShow;//監聽全局loading是否展示
}
},
2. vuex => index.js
只保留有關loading的代碼
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
//要設置的全局訪問的state對象
const state={
//要設置的初始屬性值
jumpLoading: false
};
//實時監聽state值的變化(最新狀態)
const getters = {
//方法名隨意,主要是來承載變化的showFooter的值
isLoadingShow(state) {
return state.jumpLoading
}
};
const mutations = {
//自定義改變state初始值的方法,這裏面的參數除了state之外還可以再傳額外的參數(變量或對象);
loadingShow(state) {
state.jumpLoading = true;
},
loadingHide(state) { //同上
state.jumpLoading = false;
}
};
//自定義觸發mutations裏函數的方法,context與store 實例具有相同方法和屬性
const actions = {
loadingShow(context) {
context.commit('loadingShow');
},
loadingHide(context) {
context.commit('loadingHide');
}
};
const userStore = new Vuex.Store({
state,
getters,
mutations,
actions
});
export default userStore;
2. 使用(如:login.vue)
login(){
let that = this
that.$store.dispatch('loadingShow') //展示全局loading
loginURL(param,(res)=>{
that.$store.dispatch('loadingHide') //隱藏全局loading
})
}
//或者使用
this.$store.commit('loadingShow')//顯示
this.$store.commit('loadingHide')//隱藏