KO EN

Using Pinia in Nuxt3

by Lovefield

Front End /

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

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 setting

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"

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.

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

Author

Lovefield

Lovefield

Web Front-End developer

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

로그인

디코에 오신 것을 환영해요!
전문가들의 수많은 아티클 창고 🤓