Nuxt3安装pinia

Gary Chen
Nuxt3安装pinia

在 Nuxt 3 中使用 Pinia 的步骤如下:

1. 安装 Pinia

在项目中安装 pinia@pinia/nuxt

yarn add pinia @pinia/nuxt

或者使用 npm:

npm install pinia @pinia/nuxt

2. 配置 Nuxt

nuxt.config.ts 文件中添加 @pinia/nuxt 模块:

export default defineNuxtConfig({
  modules: ['@pinia/nuxt'],
})

3. 创建 Pinia Store

在项目根目录下创建一个 stores 文件夹,并在其中创建一个 .ts 文件(例如 counter.ts):

// stores/counter.ts
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  actions: {
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
  },
});

4. 在组件中使用 Store

在 Vue 组件中,可以通过 useCounterStore 来访问和操作状态:

<template>
  <div>
    <p>Counter: {{ count }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
const { count } = storeToRefs(store); // 使用 storeToRefs 保持响应性
const { increment, decrement } = store;
</script>

5. 使用计算属性保持响应性

如果需要从 store 中提取特定属性,建议使用 computedstoreToRefs,以确保响应性:

import { computed } from 'vue';
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
const count = computed(() => store.count);

或者使用 storeToRefs

import { storeToRefs } from 'pinia';
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
const { count } = storeToRefs(store);

6. 其他高级用法

  • 持久化状态:可以使用 pinia-plugin-persistedstate/nuxt 插件来持久化状态。
  • 自定义序列化/反序列化:可以通过在 store 中定义 serializedeserialize 方法来实现。

通过以上步骤,你可以在 Nuxt 3 项目中高效地使用 Pinia 进行状态管理。