Pinia基本使用
馨er BOSS

Pinia快速入门

1 什么是Pinia

Pinia 是一个用于 Vue 的状态管理库,类似 Vuex, 是 Vue 的另一种状态管理方案,被称为Vuex5.0

Pinia 支持 Vue2 和 Vue3

Pinia中文文档(非官方)

2 Pinia优势

  • 符合直觉,易于学习
  • 极轻,仅有1KB
  • 模块化设计,便于拆分状态

3 安装Pinia

1
2
3
4
# 使用 npm
npm install pinia@next
# 使用 yarn
yarn add pinia@next

创建一个 pinia(根存储)并将其传递给应用程序:

1
2
3
import { createPinia } from 'pinia';

app.use(createPinia());

4 核心概念与基本使用

4.1 Store

Store 是一个保存状态和业务逻辑的实体,可以自由读取和写入,并通过导入后在 setup 中使用

创建一个 store

1
2
3
4
5
6
7
8
9
10
11
12
// store/index.js
import { defineStore } from "pinia";

// defineStore 调用后返回一个函数,调用该函数获得 Store 实体
export const useStore = defineStore({
// id: 必须的,在所有 Store 中唯一
id: "myGlobalState",
// state: 返回对象的函数
state: ()=> ({
count: 1
}),
});

4.2 使用 Store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// xxx.vue
<template>
<div>
{{store.count}}
</div>
</template>
<script>
// 导入 Store, 使用自己的路径
import { useStore } from "@/store/index.js";
export default {
setup() {
// 调用函数 获得Store
const store = useStore();
return {
store
}
}
}
</script>

4.3 Getters

Pinia 中的 Getters 作用与 Vuex 中的 Getters 相同,但使用略有差异

Pinia 中的 Getters 直接在 Store 上读取,形似 Store.xx,就和一般的属性读取一样

4.4 Getter基本使用

Getter 第一个参数是 state,是当前的状态,也可以使用 this.xx 获取状态
Getter 中也可以访问其他的 Getter, 或者是其他的 Store 例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 修改 store.js
import { defineStore } from "pinia";

import { useOtherStore } from "@/store/otherStore.js";

export const useStore = defineStore({
// 唯一标识这个store实体
id: "myGlobalState",
state: () => ({
count: 2
}),
getters: {
// 一个基本的 Getter: 计算 count 的平方
// 使用参数
countPow2(state) {
return state.count ** 2;
},
// 使用 this
/*
countPow2() {
return this.count ** 2;
},
*/
// 简单的 Getter 直接使用箭头函数
// countPow2: state => state.count ** 2

// 获取其它 Getter, 直接通过 this
countPow2Getter() {
return this.countPow2;
},

// 使用其它 Store
otherStoreCount(state) {
// 这里是其他的 Store,调用获取 Store,就和在 setup 中一样
const otherStore = useOtherStore();
return otherStore.count;
},
}
});
1
2
3
4
5
6
7
8
9
// otherStore.js
import { defineStore } from "pinia";

export const useOtherStore = defineStore({
id: "otherState",
state: ()=> ({
count: 5
}),
});

4.5 actions

Pinia 没有 Mutations,统一在 actions 中操作 state,通过this.xx 访问相应状态

虽然可以直接操作 Store,但还是推荐在 actions 中操作,保证状态不被意外改变

action 和普通的函数一样,action 同样可以像 Getter 一样访问其他的 Store,同上方式使用其它 Store

4.6 action基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// store.js
export const useStore({
state: () => ({
count: 2,
// ...
})
// ...
actions: {
countPlusOne() {
this.count++;
},
countPlus(num) {
this.count += num;
}
}
})

5 总结

Pinia 相比 Vuex 更加简单,而且 Pinia 可以自由扩展 官方文档 Plugins

Pinia 是符合直觉的状态管理方式,让使用者回到了模块导入导出的原始状态,使状态的来源更加清晰可见

  • 本文标题:Pinia基本使用
  • 本文作者:馨er
  • 创建时间:2022-08-03 13:48:32
  • 本文链接:https://sjxbbd.vercel.app/2022/08/03/cc325ebfbc90/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!