Vue.js 是一个非常流行的前端框架,它的状态管理方案 Vuex 在应用开发中被广泛使用。但是,随着 Vue3 的发布,一个新的状态管理库 Pinia 也出现在了我们的视野中。
在本文中,我们将会详细介绍什么是 Pinia,以及如何在 Vue 3 中使用 Pinia。
1、什么是 Pinia
Pinia 是一个基于 Vue 3 的状态管理库,提供了一种简单、直接、自然的状态管理方式。Pinia 的核心概念是 Store,Store 是一个具有响应式能力的数据容器,其中存储了整个应用程序的状态。
与 Vuex 不同,Pinia 并不强制要求开发者使用 Mutation 和 Action 等概念来进行状态的管理,而是通过提供了一些 API 来完成数据的操作。
相比于 Vuex,Pinia 更加轻量化、灵活和易用,并且能够与 Vue 3 的新特性 Composition API 配合更好地协作。
2、如何使用 Pinia
接下来,我们将通过一个例子来演示如何在 Vue 3 中使用 Pinia。
安装 Pinia
首先,我们需要安装 Pinia。
npm install pinia
创建 Store
接下来,我们需要创建一个 Store。在 Pinia 中,一个 Store 可以简单地理解为一个包含状态的容器。
在index文件中创建一个大仓库
import { createPinia } from 'pinia'
// 创建大仓库
const store = createPinia()
// 导出大仓库
export default store
在main文件中引入store
// 引入仓库
import store from "./store/index";
// 注册仓库
app.use(store)
在modules文件夹下创建一个count.ts文件
import { defineStore } from 'pinia'
// 创建小仓库
const useCountStore = defineStore('counter',{
// 定义状态
state: () => ({
count: 0
}),
// 定义修改状态的方法
actions: {
increment() {
this.count++ // `this` 指向 store 实例
},
decrement(num: number) {
this.count -= num // 可以传入额外的参数
}
},
// 定义获取状态的方法
getters: {
doubleCount() {
return this.count * 2
}
}
})
// 导出小仓库
export default useCountStore
在上面的代码中,我们通过 `defineStore` 方法创建了一个名为 `useCounterStore` 的 Store。其中,`id` 是一个唯一的标识符,可以用来跨 Store 之间进行通信。
在 Store 中,我们定义了一个名为 `count` 的状态,以及两个名为 `increment` 和 `decrement` 的操作。这两个操作可以通过 `this` 来访问当前 Store 中的状态,从而实现对状态的变更。
另外,我们还定义了一个名为 `doubleCount` 的 getter,它可以根据 `count` 计算得出当前 `count` 的两倍。
在组件中使用 Store
接下来,我们将在组件中使用上面创建的 Store。
import { defineStore } from 'pinia'
// 创建小仓库
export const useCountStore = defineStore('counter',{
// 定义状态
state: () => ({
count: 0
}),
// 定义修改状态的方法
actions: {
increment() {
this.count++ // `this` 指向 store 实例
},
decrement(num: number) {
this.count -= num // 可以传入额外的参数
}
},
// 定义获取状态的方法
getters: {
doubleCount(): number {
return this.count * 2
}
}
})
在上面的代码中,我们通过 `useCounterStore` 方法获取到了 `useCounterStore` Store 的实例。然后我们可以通过 `counter.count` 访问到当前 Store 中的状态,以及通过 `counter.increment()` 和 `counter.decrement()` 来调用相应的操作。
需要注意的是,在 Vue 3 中我们使用 Composition API 来访问 Store 实例,而不是像在 Vuex 中那样通过 $store
来访问。
在页面中使用
<script setup lang="ts">
// 引入store
import { useCountStore } from './store/modules/count'
// 使用store
const countStore = useCountStore()
</script>
<template>
<div>
<h1>count: {{ countStore.count }}</h1>
<h1>doubleCount: {{ countStore.doubleCount }}</h1>
<button @click="countStore.increment">+</button>
<button @click="countStore.decrement(10)">-</button>
</div>
</template>
3、总结
在本文中,我们详细介绍了什么是 Pinia 以及如何在 Vue 3 中使用 Pinia。相比于 Vuex,Pinia 更加轻量化、灵活和易用,并且能够与 Vue 3 的新特性 Composition API 配合更好地协作。
如果你正在学习 Vue 3 或者正在寻找一种简单、直接、自然的状态管理方式,那么 Pinia 绝对是一个很不错的选择。