繁体   English   中英

Nuxt.js vuex 存储未持久化

[英]Nuxt.js vuex store not persisted

我的 Nuxt.js 设置有一些奇怪的问题。 Store 中的某些状态不是持久的,每次我加载另一个视图时,它们都会返回默认值。

页面/test.vue

<template>
  <section class="section">
    <b-container>
      <b-row>
        <b-col cols=12>
          <b-button @click="setTest" variant="dark">test</b-button> | {{this.$store.state.test}} |
        </b-col>
      </b-row>
    </b-container>
  </section>
</template>

<script>
export default {
  name: 'test',
  methods: {
    setTest() {
      this.$store.commit("setTest")
    },
  }
}
</script>

存储/index.js

export const state = () => ({
  test: "test"
})

export const mutations = {
  setTest: (state) => state.test = 'Hello'
}

测试场景是点击“测试”按钮,该按钮使用突变提交“setTest”调用该方法,该方法将 state 设置为“Hello”。 目前它工作正常,但如果我更改视图或重新加载页面,state 将设置为默认“测试”。

我究竟做错了什么?

好吧,所以行为完全是合乎逻辑的。 Vuex 不应该是持久的。

对于前端的任何持久性,您需要:

  • cookies
  • 本地存储
  • 在 URL 中传递它(查询参数)
  • 索引数据库
  • 通过调用后端获取数据

这里的一些包可能有用: https://github.com/vuejs/awesome-vue#persistence


如果您使用 F5 重新加载页面,您的所有 JS 将被擦除并再次加载。 因此,不会保留 state ,因为它将是一个全新的页面。 使用前端框架时,您不能期望它只在页面刷新后才能工作。

当您跟随href时,同样的 go 是真正的导航。 您需要做的是使用<nuxt-link></nuxt-link>组件,使用类似于to="/profile"的内容让 VueJS 移动到这个 URL。

NuxtLink是一个 Nuxt.js 组件,本质上是<router-link></router-link>之上的一个组件,它是Vue 路由器

TLDR:您不能使用window.location.href类的东西,也不能使用<a href="..." 如果您仅使用 VueJS,您可以通过 Nuxt ( nuxt-link ) 或 Vue 的路由器 ( router-link ) 使用给定的组件。

阅读 Vue 路由器的文档可能是了解更多内容的良好开端!


如果您使用的是nuxt/auth ,请尝试一下: https://auth.nuxtjs.org/api/storage/#universal-storage

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM