Learn how to use Composeable to call Pinia store in Nuxt 3
P粉418351692
P粉418351692 2023-08-26 09:34:11
0
2
693
<p>Since nuxt 3.4.0 update, pinia store cannot be used in composeables. </p> <pre class="brush:php;toolbar:false;">//Example composeable import { useAuthStore } from '~/store/auth-store'; const authStore = useAuthStore(); export function doSomethingWithStore() { return authStore.checkAuthUser; }</pre> <p>You will receive the following error</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>View stackblitz example https://stackblitz.com/edit/broken-pinia-store-in-composeables?file=composables/thisBreaks.js,nuxt.config.ts</p>
P粉418351692
P粉418351692

reply all(2)
P粉186897465

You installed the @pinia/nuxt module incorrectly in nuxt.config.ts. In Nuxt 3, the buildModules attribute no longer exists and you need to use modules instead (you can tell by the TypeScript error):

// nuxt.config.ts
export default defineNuxtConfig({
  // replace buildModules by modules
  modules: ['@pinia/nuxt'],
});

Second point, you also need to call useAuthStore inside the combiner function, otherwise it will try to load the store before pinia actually loads. It is called when the file is imported, not when the combiner function is used.

import { useAuthStore } from '~/store/auth-store';

export function doSomethingWithStore() {
  const authStore = useAuthStore();
  return authStore.checkAuthUser;
}

Please refer to this working stackblitz

P粉378264633

This is because declaring const authStore = useAuthStore(); outside of any function like you did will be called at some early stage of application startup, and correctly within the Vue instance Before initializing the Pinia instance.

This will work:

import { useAuthStore } from '~/store/auth-store';

export function doSomethingWithStore() {
  const authStore = useAuthStore();
  return authStore.checkAuthUser;
}

Places where it is safe to make Pinia calls (may not be a complete list):

  • Inside<script setup>Internal
  • Inline in <template> section
  • In defineNuxtMiddlewareInternal
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!