【问题标题】:Check if vuex-persist has restored data in Nuxt project检查 vuex-persist 是否已恢复 Nuxt 项目中的数据
【发布时间】:2020-04-06 10:54:35
【问题描述】:

我已将 Vuex-Persist 和 Vuex-ORM 添加到我的 Nuxt 项目中。当应用程序第一次启动时,我想添加一些样板数据。

在我的default.vue 布局中,我添加了一个创建函数来添加这个虚拟数据。

<script>
import Project from '../models/Project';

export default {
  created () {
    // I'm Using Vuex-Orm to check if there are any projects stored
    if (Project.query().count() === 0) {
      Project.insert({ data: [{ title: 'My first project' }] })
    }
  }
}
</script>

当应用程序重新加载并第二次打开时,我希望Project.query().count() 返回 1。但它总是返回 0,因为 vuex-persist 还没有完成恢复本地数据。

根据the docs ,这将是解决方案

import { store } from '@/store' // ...or wherever your `vuex` store is defined

const waitForStorageToBeReady = async (to, from, next) => {
  await store.restored
  next()
}

store.defined 未定义,this.$store 也是如此。 该评论突出了我的确切问题“我的 vuex 商店在哪里定义?”

【问题讨论】:

    标签: vue.js vuex nuxt.js


    【解决方案1】:

    我认为你必须把整个东西放在一个路线守卫中。

    像这样创建一个 route-guard.js 插件。但我还没有测试整个东西,希望它可以进一步帮助你。

    export default function ({app}) {
    
        const waitForStorageToBeReady = async (to, from, next) => {
            await store.restored
            next()
        }
    
        app.router.beforeEach(waitForStorageToBeReady);
    }
    

    另一种选择是在计算中放入一个 getter 并观察它:

    export default {
    
        computed: {
            persistState() {
                return this.store.getter['get_persis_state'];
            }
        },
    
        watch: {
            persistState(newVal) {
                // check new val
            }
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      我从 vuex-persist 关注 the instructions 为 Nuxt 制作了一个插件文件,如下所示:

      // ~/plugins/vuex-persist.js
      import VuexPersistence from 'vuex-persist'
      
      export default ({ store }) => {
        window.onNuxtReady(() => {
          new VuexPersistence({
          /* your options */
          }).plugin(store);
        });
      }
      

      window.onNuxtReady 导致插件在所有其他代码运行后加载。所以我不管我是做一个router-guard.js插件还是在layout/default.vue文件中尝试。

      我最终得到了快速修复:

      // ~/plugins/vuex-persist.js
      import VuexPersistence from 'vuex-persist'
      
      export default ({ store }) => {
       window.onNuxtReady(() => {
          new VuexPersistence().plugin(store);
      
          if (Project.query().count() === 0) {
            Project.insert({ data: [{ title: 'My first project' }] })
          }
        });
      }
      

      【讨论】:

        猜你喜欢
        • 2021-02-03
        • 2020-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-23
        • 2010-10-28
        • 1970-01-01
        相关资源
        最近更新 更多