How to use Pinia in Nuxt

Nuxt guide logo

Pinia in Nuxt

Pinia is a store library for Vue and Nuxt , it allows you to share a state across components/pages

Run the command below to install Pinia for Nuxt.

yarn add @pinia/nuxt

Adding module

Add Pinia module to nuxt.config.ts. (choose one from the two steps below).

1.

                                
                                        // ...
modules: ['@pinia/nuxt'],
pinia: {
  autoImports: [
    // automatically imports `defineStore`
    'defineStore', // import { defineStore } from 'pinia'
  ],
},
                                    
                            

2.

                                
                                        // ...
modules: [
  [ '@pinia/nuxt',
    {
      autoImports: [
        // automatically imports `defineStore`
        'defineStore',
     ]
    }
  ],
  // other module
]
                                    
                            

Creating a Nuxt's Store

In the root of the Nuxt project create a store folder, then inside the store folder create an index.ts file.

Index file inside store folder
Index file inside store folder

Initiate Nuxt's Store

Now the initiation of the Store in the index.ts file.

                                
                                        export const useMainStore = defineStore('main', () => {
  // - ref()s become state properties
  // - computed()s become getters
  // - function()s become actions
  const isLoading = ref<boolean>(true);
  const loadingStatus = computed(() => isLoading.value);
  
  return {
    isLoading,
    loadingStatus
  };
});
                                    
                            

Accessing Store from Nuxt application

Now anywhere in the Nuxt application, it can access the Store.

                                <template>
  <main>
    <Loader v-if="mainStore.loadingStatus" />
   </main>
</template>
                            
                                
                                        <script lang="ts" setup>
  import { useMainStore } from '@/store';
  const mainStore = useMainStore();
</script>
                                    
                            
Previous post How to build a local API route in Nuxt 3
Next post How to get current route name in Nuxt