【问题标题】:How to Implement nuxtServerInit Action to load data from server-side on the initial load in Pinia (Nuxt3)如何实现 nuxtServerInit Action 以在 Pinia (Nuxt3) 的初始加载时从服务器端加载数据
【发布时间】:2022-06-15 01:41:50
【问题描述】:

我的代码:

export const useMenuStore = defineStore("menuStore", {
  state: () => ({
    menus: [],
  }),
  actions: {
    async nuxtServerInit() {
     
       const { body } = await fetch("https://jsonplaceholder.typicode.com/posts/1").then((response) => response.json());
       console.log(body);
       this.menus = body;
       resolve();
    },
   
  },
});

NuxtServerInit 无法在 nuxt js vuex 模块模式下进行初始页面渲染。任何知道此错误的人请帮助我。

【问题讨论】:

  • 指定“不工作”

标签: vuex vuejs3 nuxtjs3 pinia nuxtserverinit


【解决方案1】:

NuxtServerInit 未在 Pinia 中实现,但存在一种解决方法。

将 Pinia 与 Vuex 一起使用

// nuxt.config.js
export default {
  buildModules: [
    '@nuxtjs/composition-api/module',
    ['@pinia/nuxt', { disableVuex: false }],
  ],
  // ... other options
}

然后在 /stores 中包含一个 index.js 文件,其中包含一个 nuxtServerInit 操作,该操作将在初始加载时从服务器端调用。

// store/index.js
import { useSessionStore } from '~/stores/session'

export const actions = {
  async nuxtServerInit ({ dispatch }, { req, redirect, $pinia }) {
    if (!req.url.includes('/auth/')) {
      const store = useSessionStore($pinia)

      try {
        await store.me() // load user information from the server-side before rendering on client-side
      } catch (e) {
        redirect('/auth/login') // redirects to login if user is not logged in
      }
    }
  }
}

【讨论】:

    猜你喜欢
    • 2022-12-04
    • 2017-05-25
    • 2019-04-04
    • 2018-11-19
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    相关资源
    最近更新 更多