开始
Pinia是Vue3的状态管理库,安装Pinia命令:npm i pinia
在main.ts
中引入Pinia
1 | import { createApp } from 'vue'; |
数据存储
在src目录下创建store目录,其中每个组件对应一个.ts文件,存储每个组件的响应式数据
定义数据存储store
1 | import {defineStore} from "pinia"; |
使用store
1 | <script setup lang="ts"> |
数据修改
-
直接修改:直接获取数据进行修改
1
countStore.count += 1;
-
patch方法:通过
$patch
方法批量修改1
2
3countStore.$patch({
count: 2,
}) -
actions选项:在配置对象中设置actions选项,其中定义修改数据的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import {defineStore} from "pinia";
export const useCountStore = defineStore("count", {
state() {
return {
count: 0
}
},
actions: {
// 通过this获取数据
setCount(value: number) {
this.count = value;
}
}
});
// 外部调用方法
// countStore.setCount(2);
storeToRefs
将store中的响应式数据解构转换为ref类型
1 | import {storeToRefs} from "pinia"; |
getters选项
用于定义计算属性
1 | import {defineStore} from "pinia"; |
$subscribe方法
$subscribe
方法用于监视store中的数据变化
1 | // 通过state参数获取变化后数据 |
组合式store
使用组合式写法定义store
1 | import {defineStore} from "pinia"; |