zoukankan      html  css  js  c++  java
  • vue keep-alive与mapState的填坑记录

    最近在用keep-alive配合vuex做缓存处理。发现在某些场景下,keep-alive设置的include不会立即生效,但是include的值确实已经改变。
      具体的原因如下。在router.beforeEach中dispatch关于keep-alive的action,在action中根据路由对state中的include动态增删。然后在相应的页面组件中mapState获取该include。我发现路由的跳转优先于mapState获取include,导致缓存不会立即生效。由此可见mapState获取值应该是异步的。
      解决办法,在action中使用promise包装,在router.beforeEach使用await或者.then实现同步,保证include修改完成并mapState到组件中,再进行路由的跳转。
      出现该问题的场景如下图:
    场景
      点切换左侧导航时,清空store中的include,重新点击下钻并动态修改include。此时,返回上一页面会重新发起网络请求,缓存失效!
      我发现生命周期即进入了created,也进入了activated。也就是说state中include的修改晚于router的跳转。怀疑在router.beforeEach拦截处理include时,出现了异步,导致路由优先进入然后组件才通过mapState获取到新的include的值。
      于是,我将action中操作include的函数使用primise封装起来,如下:

    const actions = {
      changeKeepAlive({ commit }, { to, from }) {
        return new Promise((resolve, reject) => {
          if (!to.path.includes('/home/menu')) { // 不是首页, 清空keepalive
            commit('CLEAR_INCLUDE');
            resolve();
          } else {
            let fromIsInKeepAlive = state.include.includes(from.name);
            if (to.meta.index < from.meta.index && fromIsInKeepAlive) {  // 后退时,若当前页被缓存,移除缓存配置
              commit('DELETE_INCLUDE', from.name);
              resolve();
            }
            if (to.meta.index > from.meta.index && !fromIsInKeepAlive) {  // 前进时,下一页需要缓存,添加该页面
              commit('ADD_INCLUDE', from.name);
              resolve();
            }
          }
          resolve();
        });
      }
    };
    store.dispatch('keepAlive/changeKeepAlive', {to, from}).then(() => {
        ...
    })

    ude需要在路由跳转前修改。

    漫思
  • 相关阅读:
    Spring中的destroy-method方法
    github Pull Request合入全流程介绍
    vue-router动态路由设置参数可选
    github上fork原项目,如何将本地仓库代码更新到最新版本?
    github的pull Request使用
    vue2.X版本vue-cli生成项目后运行失败,报错信息为getaddrinfo ENOTFOUND localhost
    npm在linux即mac下更新时报错
    数组Array和字符串String的indexOf方法,以及ES7(ES2016)中新增的Array.prototype.includes方法
    less的使用总结
    ssh连接github连不上
  • 原文地址:https://www.cnblogs.com/sexintercourse/p/13411147.html
Copyright © 2011-2022 走看看