简体   繁体   English

如何在通用渲染时在 Nuxt.js 中初始化 state,其中包括 localStorage

[英]How do I initialise state in Nuxt.js which includes localStorage while Universal Rendering

Scenario设想

First of all, let me start with my flow.首先,让我从我的流程开始。
I am storing token in localStorage (I know I shouldn't do it.) Then, whenever my Nuxt App is started, I want to fetch token from localStorage, verify it using API call, and initialise state accordingly.我将令牌存储在 localStorage 中(我知道我不应该这样做。)然后,每当我的 Nuxt 应用程序启动时,我想从 localStorage 获取令牌,使用 API 调用验证它,并相应地初始化 state。

Problem问题

I am using Server Side Rendering and Nuxt initialises state Server Side.我正在使用服务器端渲染和 Nuxt 初始化 state 服务器端。 Thus, localStorage is not accessible there.因此,localStorage 在那里无法访问。

Proposed Workaround建议的解决方法

I created an Action which does task explained in Scenario and that action is triggered from mounted() of layouts/default.vue我创建了一个动作,它执行Scenario中解释的任务,并且该动作是从layouts/default.vue的 mount() 触发的

Can Anyone Please suggest a Better Workflow or Can Verify Wether this is Correct Way of doing things?任何人都可以建议更好的工作流程或可以验证这是正确的做事方式吗?

you can use typeof window === 'undefined' to determine if it running in Server Side, and skip the code you only want to run in client, just like:您可以使用typeof window === 'undefined'来确定它是否在服务器端运行,并跳过您只想在客户端运行的代码,就像:

if (typeof window !== 'undefined') {
   // your code
}

You can use it in created / beforeCreate / asyncData , And if you code is in mounted(), you may not need do this, 'case this Lifecycle Hooks only run in the client.你可以在created / beforeCreate / asyncData中使用它,如果你的代码在mounted()中,你可能不需要这样做,'如果这个 Lifecycle Hooks 只在客户端运行。

You can write a Middleware and dispatch your action that checks the token in it and call it in the layout.您可以编写一个中间件并调度您的操作来检查其中的令牌并在布局中调用它。 https://nuxtjs.org/docs/2.x/directory-structure/middleware https://nuxtjs.org/docs/2.x/directory-structure/middleware

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

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