Vue 3 + Pinia 实现状态存储(001)

114 阅读2分钟

在 Vue 3 中,Pinia 是一个官方推荐的状态管理库,它提供了一种更轻松的方式来定义、访问和管理应用的全局状态。这篇文章将介绍如何在 Vue 3 项目中使用 Pinia,并展示两种创建 Pinia store 的方式:一种是基于官方文档的传统方式,另一种是基于组合式 API (setup()) 的方式。

安装 Pinia

在开始之前,请确保已经安装了 Pinia。如果尚未安装,可以通过以下命令进行安装:

npm install pinia

初始化 Pinia

在你的 Vue 3 项目中,初始化 Pinia 并将其作为插件添加到 Vue 中:

// main.js
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

const app = createApp(App);
app.use(createPinia());
app.mount('#app');

第一种方式:官方文档方式创建 Pinia Store

创建 Store

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

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

在组件中使用 Store

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

const counter = useCounterStore();
</script>

<template>
  <button @click="counter.increment">Count is: {{ counter.count }}</button>
</template>

第二种方式:使用组合式 API (setup()) 创建 Pinia Store

创建 Store

// stores/counterSetup.js
import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useCounterSetupStore = defineStore('counterSetup', () => {
    const count = ref(0);

    function increment() {
        count.value++;
    }

    return { count, increment };
});

在组件中使用 Store

<script setup>
import { useCounterSetupStore } from '@/stores/counterSetup';

const counter = useCounterSetupStore();
</script>

<template>
  <button @click="counter.increment">Count is: {{ counter.count }}</button>
</template>

注意事项

  • Pinia 要求 Vue 3.0+,请确保你的项目满足此版本要求。
  • 在大型应用中,合理组织你的 Store 文件,例如按功能或页面划分。
  • Pinia 支持热模块替换 (HMR),在开发过程中可以提供更好的开发体验。

结语

Pinia 提供了一种简单、直观的方式来处理 Vue 应用中的状态管理。无论是传统的方式还是利用 Vue 3 的 setup(),Pinia 的灵活性都能很好地满足不同场景的需求。通过上述两种方式,你可以根据项目需求和个人喜好选择合适的方式来创建和管理 Pinia store。