P粉1868974652023-08-27 08:07:09
您在 nuxt.config.ts
中錯誤地安裝了 @pinia/nuxt 模組。在 Nuxt 3 中,buildModules
屬性已經不存在了,您需要使用 modules
取代它(您可以透過 TypeScript 錯誤來判斷):
// nuxt.config.ts
export default defineNuxtConfig({
// replace buildModules by modules
modules: ['@pinia/nuxt'],
});
第二點,您還需要在組合函數內部呼叫 useAuthStore
,否則它會在 pinia 實際載入之前嘗試載入儲存。它會在檔案被導入時調用,而不是在組合函數被使用時調用。
import { useAuthStore } from '~/store/auth-store'; export function doSomethingWithStore() { const authStore = useAuthStore(); return authStore.checkAuthUser; }
請參考這個可工作的 stackblitz
#P粉3782646332023-08-27 00:19:28
這是因為像你所做的那樣,在任何函數之外聲明const authStore = useAuthStore();
會在應用程式啟動的某個早期階段調用,並且在Vue實例內正確初始化Pinia實例之前。
這樣做會起作用:
import { useAuthStore } from '~/store/auth-store'; export function doSomethingWithStore() { const authStore = useAuthStore(); return authStore.checkAuthUser; }
可以安全地進行Pinia呼叫的地方(可能不是完整的清單):
<script setup>
內部<template>
部分內聯defineNuxtMiddleware
內部