Min*_*Yến 5 vuex vuejs3 nuxtserverinit nuxtjs3 pinia
我的代码:
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();
},
},
});
Run Code Online (Sandbox Code Playgroud)
NuxtServerInit 无法在 nuxt js vuex 模块模式下进行初始页面渲染。任何人都知道此错误,请帮助我。
小智 1
NuxtServerInitPinia 中未实现,但存在解决方法。
将 Pinia 与 Vuex 一起使用
// nuxt.config.js
export default {
buildModules: [
'@nuxtjs/composition-api/module',
['@pinia/nuxt', { disableVuex: false }],
],
// ... other options
}
Run Code Online (Sandbox Code Playgroud)
然后在 /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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3154 次 |
| 最近记录: |