Using Pinia in Nuxt3

Nuxt

Language :

Hi, I’m Lovefield.

Nuxt2 provided Vuex by default, but this feature was removed from Nuxt3. In Nuxt3, you can use Pinia as your state manager. In this article, I'll show you how to use Pinia in Nuxt3.

Pinia install

shell

bun add @pinia/nuxt

Install the Pinia module through the command above. I will not explain it additionally because each package manager uses is diverse.

nuxt.config.ts

javascript

export default defineNuxtConfig({
   modules: [["@pinia/nuxt", { autoImports: ["defineStore"] }]],
   imports: {
       dirs: ["stores"],
   },
});

Add Pinia to the modules. Set autoImports option to automatically import function 'defineStore'. If not set, the store file must declare 'import {defineStore} from 'pinia';' to use the defineStore every time.

Set the imports option to automatically import files in the "stores" folder. This option automatically imports files so that you don't have to use unnecessary import statements.

Write "stores/global.ts"

javascript

export const useGlobalStore = defineStore("globalStore", {
   state: (): { name: string } => ({
       name: "",
   }),
   actions: {
       setName(name: string) {
           this.name = name;
       },
       resetName() {
           this.name = "";
       },
   },
});

Export the defineStore function in the useGlobalStore variable. The defineStore function must pass the factors in order of name and option.

The state property is an object that can actually be stored in the store and used. It consists of key:value and can be called from the store at any time.

The actions property is a list of functions used to control the value of the state. You can change the value of the state directly, but you don't use it that way.

The store does not revert to its initial value unless the page is refreshed.

The following is an example used on the page.

html

<template>
   <div>
       <p>{{ globalStore.name }}</p>
       <button @click="changeName">Change Name</button>
   </div>
</template>

<script setup lang="ts">
const globalStore = useGlobalStore();

function changeName() {
   if (globalStore.name === "Mario") {
       globalStore.setName("Luigi");
   } else {
       globalStore.setName("Mario");
   }
}
</script>

Lovefield

Web Front-End developer

하고싶은게 많고, 나만의 서비스를 만들고 싶은 변태스러운 개발자입니다.