搜尋

首頁  >  問答  >  主體

學習如何在Nuxt 3中使用Composeable來呼叫Pinia store

<p>自從nuxt 3.4.0更新後,無法在composeables使用pinia store。 </p> <pre class="brush:php;toolbar:false;">//範例composeable import { useAuthStore } from '~/store/auth-store'; const authStore = useAuthStore(); export function doSomethingWithStore() { return authStore.checkAuthUser; }</pre> <p>你將會收到以下錯誤</p> <pre class="brush:php;toolbar:false;">getActivePinia was called with no active Pinia. Did you forget to install pinia? const pinia = createPinia() app.use(pinia) This will fail in production. </pre> <p>查看stackblitz例子 https://stackblitz.com/edit/broken-pinia-store-in-composeables?file=composables/thisBreaks.js,nuxt.config.ts</p>
P粉418351692P粉418351692544 天前890

全部回覆(2)我來回復

  • P粉186897465

    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

    #

    回覆
    0
  • P粉378264633

    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內部

    回覆
    0
  • 取消回覆