How to use Pinia in Nuxt
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.
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>