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

查看:227
本文介绍了javascript - 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;
  },

...
}

解决方案

不要用v-if用v-show
不要用v-if用v-show
不要用v-if用v-show

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

这篇关于javascript - vue1.0+vue 异步修改store状态出现死循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆