vue1.0+vue 异步修改store状态出现死循环

业务逻辑如下:
要在页面跳转时,对需要异步获取数据的页面显示预加载动画
在数据回传后隐藏预加载动画
实现想法:
目录结构如下
图片描述

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;
  },

...
}
阅读 3.3k
2 个回答
不要用v-if用v-show
不要用v-if用v-show
不要用v-if用v-show

不然你的页面会一直载入的

使用v-if的话在created里showLoading变成true,你的view就被销毁了,等之后showLoading变成false之后,view又被创建,created又执行了,就循环执行了呀。试试用v-show或者其他的方法吧。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题