首先是store目录,目录结构如下:
index.js
// 组装模块并导出 store 的地方
import Vue from 'vue'
import Vuex from 'vuex'
import loading from './modules/loading'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
loading,
},
strict: process.env.NODE_ENV !== 'production' // 严格模式
})
loading.js
const SHOWLOADING = 'SHOWLOADING'
const HIDELOADING = 'HIDELOADING'
const state = {
showLoading: false
}
const getters = {
showLoading(state) {
return state.showLoading
}
}
const actions = {
showloader: ({ commit }) => {
commit(SHOWLOADING)
},
hideloader: ({ commit }) => {
commit(HIDELOADING)
}
}
const mutations = {
[SHOWLOADING](state) {
state.showLoading = true
},
[HIDELOADING](state) {
state.showLoading = false
}
}
export default {
state,
mutations,
actions,
getters
}
因为一般loading动画或者升级提示弹窗的显示与隐藏大多是全局使用的,所以在App.vue中控制:
App.vue--showLoading是布尔值,为了方便看文本,没有加v-show="showLoading",你们可以加在自己定义的组件中
<template>
<div id="app">
<!-- <ul>
<li>{{date1|dataServer}}</li>
</ul> -->
<router-link to="a">wedefde</router-link>
<div>加载中{{showLoading}}</div>
<router-view></router-view>
</div>
</template>
<script>
import {mapGetters,mapActions} from 'vuex';
export default {
name: 'app',
data() {
return {
date1: '2019-01-01 00:01'
}
},
computed:{
...mapGetters(['showLoading'])
}
}
</script>
<style lang="stylus">
</style>
当前编写的页面组件,为了方便,使用了延迟函数,实际情况请按逻辑使用:
<template lang="">
<div>
我是a页面-ui的子路由
</div>
</template>
<script>
import {mapGetters,mapActions} from 'vuex';
export default {
name: 'aa',
mounted() {
this.showloader();
setTimeout(() => {
this.hideloader()
}, 1200);
},
methods:{
...mapActions(['showloader','hideloader'])
}
}
</script>
<style lang="">
</style>
以上是vuex方法,虽然实现了想要的效果; 但是对于全局使用的,而且逻辑非常简单的,可以使用$bus(即window.$bus = new Vue();//注册全局事件对象,可以在main.js写明;然后使用它的$emit方法发送事件,在App.vue使用$on方法接收事件,通过不同的事件判断控制显示与隐藏的变量
$bus.$on('showLoad',()=>{
this.show=true;
})
$bus.$on('hideLoad',()=>{
this.show=false;
})
然后在需要的页面使用--为了方便,使用了延迟函数,实际情况请按逻辑来
$bus.$emit('showLoad');
setTimeout(() => {
$bus.$emit('hideLoad');
}, 2200);