为什么要在 SSR 中使用 Vuex?

Why use Vuex in SSR?

我的问题是,当客户端水化发生时状态将被覆盖时,为服务器设置 Vuex 有什么意义?

我有一些数据(Helm env 变量)要存储在 vuex 存储中供以后使用。 这些变量仅在服务器上对我可用,因此当服务器上 运行 时,我开始尝试将它们添加到我的 createApp 脚本中的商店中。 但是,当客户端水合作用开始时,存储状态将被重置,因此没有环境变量留下。

Google 告诉我应该使用 window.INITIAL_DATA 来在客户端再次设置状态: store.replaceState(window.INITIAL_DATA)

但是如果必须使用 window 对象将存储数据传递给客户端,那么在服务器上使用 Vuex 有什么意义呢? 跳过服务器上的 Vuex 开销而只在客户端上使用 Vuex 并用 INITIAL_DATA 填充它不是更好吗?

我可能漏掉了什么..

https://ssr.vuejs.org/guide/data.html#data-store

During SSR, we are essentially rendering a "snapshot" of our app. The asynchronous data from our components needs to be available before we mount the client side app - otherwise the client app would render using different state and the hydration would fail.

To address this, the fetched data needs to live outside the view components, in a dedicated data store, or a "state container". On the server, we can pre-fetch and fill data into the store while rendering. In addition, we will serialize and inline the state in the HTML after the app has finished rendering. The client-side store can directly pick up the inlined state before we mount the app.

还要提到: 如果你想跨组件共享信息,那么你在任何组件中的 SSR 访问的数据都需要来自某个地方,这就是 Vuex 的作用。