业务逻辑如下:
要在页面跳转时,对需要异步获取数据的页面显示预加载动画
在数据回传后隐藏预加载动画
实现想法:
目录结构如下
views为具体页面,app.vue为入口。
1.在store中添加showLoading字段:
const store= {
...
showLoading = false;
...
}
2.在view页面的create函数中首先执行showLoading命令(该命令通过action改变store中showLoading为true)显示加载动画,带数据回传后用hideLoading命令(该命令通过action改变store中showLoading为false)隐藏加载动画(原先是使用fetch获取数据,为了消除不必要的影响,这里直接使用setTimeout模拟):
created() {
console.log('1');
this.showLoading();
setTimeout(() => {
console.log('2');
this.hideLoading();
}, 5000);
},
app.vue:
<template>
<div id="app">
...
<loading v-if="showLoading"></loading> //loading为动画组件
<router-view v-if="!showLoading"></router-view>
</div>
</template>
在执行时,载入具体页面后,原本应该仅执行1次的create函数出现了循环执行,重复输出1,2也就是说他在不断显示隐藏loading模块。
应该并没有写出不知道问题在哪里?
action:
...
export const showLoading = ({ dispatch }) => {
dispatch('SHOW_LOADING');
};
export const hideLoading = ({ dispatch }) => {
dispatch('HIDE_LOADING');
};
...
mutations:
const mutations = {
...
SHOW_LOADING() {
state.showLoading = true;
},
HIDE_LOADING() {
state.showLoading = false;
},
...
}
不然你的页面会一直载入的