首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Pinia (Nuxt3)中实现从服务器端加载数据的Nuxt3操作

如何在Pinia (Nuxt3)中实现从服务器端加载数据的Nuxt3操作
EN

Stack Overflow用户
提问于 2022-06-04 07:28:27
回答 1查看 805关注 0票数 2

我的代码:

代码语言:javascript
运行
复制
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模块上进行初始页面呈现,mode.Anyone知道这个错误,请帮助我。

EN

回答 1

Stack Overflow用户

发布于 2022-06-14 17:41:50

NuxtServerInit不是在Pinia实现的,但存在一个解决方案。

与Vuex一起使用半夏

代码语言:javascript
运行
复制
// nuxt.config.js
export default {
  buildModules: [
    '@nuxtjs/composition-api/module',
    ['@pinia/nuxt', { disableVuex: false }],
  ],
  // ... other options
}

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

代码语言:javascript
运行
复制
// 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
      }
    }
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72497896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档