简体   繁体   English

Nuxt 不应该在渲染和返回页面之前更新 Vuex state 吗?

[英]Shouldn't Nuxt update Vuex state before rendering and returning a page?

Need some clarity regarding Vuex and SSR here.这里需要一些关于 Vuex 和 SSR 的说明。 Don't know what concept I'm not getting right since this is my first time working with SSR.因为这是我第一次使用 SSR,所以不知道我没有正确理解什么概念。 I'm trying to create breadcrumbs for my application using the store.我正在尝试使用商店为我的应用程序创建面包屑。 The concept is that the parent component will show the breadcrumbs and children components will set the breadcrumbs in the store.这个概念是父组件将显示面包屑,子组件将在商店中设置面包屑。 Now, whenever the server renders, it is only rendering the initial state of the breadcrumb and only updating after hydration, resulting in wrong breadcrumbs for a few seconds.现在,每当服务器渲染时,它只渲染面包屑的初始 state 并且只在水合后更新,导致几秒钟的面包屑错误。

In pseudocode:在伪代码中:

Parent.vue父.vue

<template>
  <div>
    <div>{{ $store.breadcrumbs }}</div>
    <child />
  </div>
</template>

Child.vue孩子.vue

created() {
  console.log("Component created)
  $store.setBreadcrumbs("This / is / a / test / breadcrumb")
}

Shouldn't the parent component only render after all children have been created?父组件不应该只在创建所有子组件后才呈现吗? How does that lifecycle work and how can I guarantee that the parent will be updated before sending the response from the server?该生命周期如何工作,我如何保证在从服务器发送响应之前更新父级?

Edit:编辑:

Created an example that shows the behavior https://codesandbox.io/s/vuex-module-test-dmoe6?file=/pages/index.vue创建了一个示例来显示行为https://codesandbox.io/s/vuex-module-test-dmoe6?file=/pages/index.vue

You can see that the state userName is only updated after a few moments showing "NoName" the initialized state value before updating it to JohnDoe.您可以看到 state 用户名仅在显示“NoName”初始化 state 值之后才更新,然后将其更新为 JohnDoe。

  • Add wrapper for parent and child as templates must have a single root element.为父级和子级添加包装器,因为模板必须具有单个根元素。
  • Yes, parent should be mounted after all children were created.是的,应该在创建所有子代之后挂载父代。
  • Parent-child lifecycles 父子生命周期
  • Try to use getter instead of directly calling store尝试使用getter而不是直接调用store

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

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