Jon*_*nas 5 vue.js vuex nuxt.js
I was wondering whats the best way to do something like nuxtClientInit. I'm trying to load the Auth State as early as possible on the client and save it in my vuex store but not on the server side. It would be great if vuex had something like the created hook for components but that doesn't exist to my knowledge.
How could I achieve this behavior? One way could be calling an action from a layout but is that the best way?
我知道 nuxt 团队正在开发 nuxtClientInit 功能,但在他们发布之前,您可以自己制作。要了解在有请求时 nuxt 执行的工作流程,您可以在此处查看生命周期。这表明首先调用 nuxtServerInit 然后调用中间件。在此中间件调用期间,会提供 nuxt.config.js,其中包含您的自定义配置。其中一部分是“插件”,正如文档所说,
此选项允许您定义在实例化根 Vue.js 应用程序之前应运行的 JavaScript 插件。
因此,如果您编写一个插件来调用存储操作,则可以从那里获取和设置本地存储。因此,从 nuxt-client-init 插件开始:
//nuxt-client-init.client.js
export default async context => {
await context.store.dispatch('nuxtClientInit', context)
}
Run Code Online (Sandbox Code Playgroud)
然后将插件添加到 nuxt.config.js:
//nuxt.config.js
plugins: [
'~/plugins/nuxt-client-init.client.js'
],
Run Code Online (Sandbox Code Playgroud)
如果你注意到这里的命名约定,插件的 .client.js 部分告诉 nuxt 这是一个仅限客户端的插件并且是它的简写'{ src: '~/plugins/nuxt-client-init.js', mode: 'client' }',因为 nuxt 2.4 是定义旧'{ src: '~/plugins/nuxt-client-init.js', ssr: false }'. 无论如何,您现在可以调用您的存储,因此您可以从本地存储调用操作并设置状态项。
//store/index.js
export const actions = {
nuxtClientInit({ commit }, { req }) {
const autho = localStorage.getItem('auth._token.local') //or whatever yours is called
commit('SET_AUTHO', autho)
console.log('From nuxtClientInit - '+autho)
}
}
Run Code Online (Sandbox Code Playgroud)
您可能需要重新启动您的应用程序才能使其全部生效,但您随后将获得并使用您的身份验证状态,而无需进行任何讨厌的 nuxtServerInit 业务。
| 归档时间: |
|
| 查看次数: |
4118 次 |
| 最近记录: |