Pinia (/piːnjʌ/)是一款类型安全、可扩展以及模块化设计的 Vue.js 状态管理库。

Pinia 应用示例

通过 defineStore 先创建一个 Store:

stores/counter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
state: () => {
return { count: 0 };
},
// 也可以这样定义
// state: () => ({ count: 0 })
actions: {
increment() {
this.count++;
}
}
});

在组件中引入该 Store 并使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script setup>
// setup() 函数
import { useCounterStore } from '@/stores/counter';
const counter = useCounterStore();
counter.count++;
// 自动补全
counter.$patch({ count: counter.count + 1 });
// 或使用 action 代替
counter.increment();
</script>
<template>
<!-- 直接从 store 中访问 state -->
<div>Current Count: {{ counter.count }}</div>
</template>

Pinia 也提供了一组类似 Vuex 的映射 state 的辅助函数:

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
const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
double: state => state.count * 2
},
actions: {
increment() {
this.count++;
}
}
});

const useUserStore = defineStore('user', {
// ...
});

export default defineComponent({
computed: {
// 其他计算属性
// ...
// 允许访问 this.counterStore 和 this.userStore
...mapStores(useCounterStore, useUserStore),
// 允许读取 this.count 和 this.double
...mapState(useCounterStore, ['count', 'double'])
},
methods: {
// 允许读取 this.increment()
...mapActions(useCounterStore, ['increment'])
}
});

Pinia 应用方式

使用包管理器安装 Pinia:

  • Yarn: yarn add pinia
  • NPM: npm install pinia

Pinia 使用到了组合式 API,如果你是用的 Vue<2.7版本,还需要安装组合式API包: @vue/composition-api

在 Vue3 中,创建一个 pinia 实例 并将其传递给应用:

1
2
3
4
5
6
7
8
9
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

const pinia = createPinia();
const app = createApp(App);

app.use(pinia);
app.mount('#app');

在 Vue2 中,还需要安装一个插件:

1
2
3
4
5
6
7
8
9
10
11
12
13
import { createPinia, PiniaVuePlugin } from 'pinia';

Vue.use(PiniaVuePlugin);
const pinia = createPinia();

new Vue({
el: '#app',
// 其他配置...
// ...
// 请注意,同一个`pinia'实例
// 可以在同一个页面的多个 Vue 应用中使用。
pinia
});

Pinia 概念

Store

Store 是一个保存状态和业务逻辑的实体,它并不与你的组件树绑定,承载着全局状态。一个 Store 应该包含可以在整个应用中访问的数据,你应该避免在 Store 中引入那些原本可以在组件中保存的本地数据。

Store 是用 defineStore() 定义的,它的第一个参数要求是一个唯一的名字,用作id,返回一个函数,为了符合组合式函数风格,通常命名为 use<id>StoredefineStore() 的第二个参数可接受两类值:Setup 函数或 Option 对象

当第二个参数使用 Option 对象时,可以传入一个带有 stateactiongetters 属性的 Option 对象。

1
2
3
4
5
6
7
8
9
10
11
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
double: state => state.count * 2
},
actions: {
increment() {
this.count++;
}
}
});

第二个参数使用 Setup 函数时,该函数定义了一些响应式属性和方法,并且返回一个带有我们想暴露出去的属性和方法的对象:

1
2
3
4
5
6
7
8
export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
function increment() {
count.value++;
}

return { count, increment };
});

在 Setup Store 中:

  • ref() 就是 state 属性
  • computed() 就是 getters
  • function() 就是 actions

Store 在使用 <script setup> 调用 useStore() (或者调用 setup() 函数)时,会被创建。

1
2
3
4
5
<script setup>
import { useCounterStore } from '@/stores/counter';
// 可以在组件中的任意位置访问 `store` 变量
const store = useCounterStore();
</script>

为了从 store 中提取属性时保持其响应性,你需要使用 storeToRefs(),它将为每一个响应式属性创建引用。

1
2
3
4
5
6
7
8
9
10
<script setup>
import { storeToRefs } from 'pinia';
const store = useCounterStore();
// `name` 和 `doubleCount` 是响应式的 ref
// 同时通过插件添加的属性也会被提取为 ref
// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
const { name, doubleCount } = storeToRefs(store);
// 作为 action 的 increment 可以直接解构
const { increment } = store;
</script>

State

state 被定义为一个返回初始状态的函数,代表了应用中的状态。

默认情况下,可以通过 store 实例访问 state,并进行读写。

1
2
const store = useStore();
store.count++;

使用选项式 API 时,可以通过调用 $reset 方法将 state 重置。

1
2
const store = useStore();
store.$reset();

可以通过调用 $patch 方法同时修改多个属性:

1
2
3
4
5
store.$patch({
count: store.count + 1,
age: 120,
name: 'DIO'
});

$patch 方法也接受一个函数来对集合进行修改:

1
2
3
4
store.$patch(state => {
state.items.push({ name: 'shoes', quantity: 1 });
state.hasChanged = true;
});

你不能完全替换掉 store 的 state,因为那样会破坏其响应性。但是,你可以通过 $patch 方法替换它:

1
2
3
4
// 这实际上并没有替换`$state`
store.$state = { count: 24 };
// 在它内部调用 `$patch()`:
store.$patch({ count: 24 });

你可以通过 store 的 $subscribe 方法侦听 state 及其变化,相当于组件中的 watch(), 比起普通的 watch(),使用 $subscribe() 的好处是 subscriptions 在 patch 后只触发一次 (例如,当使用上面的函数版本时)。

Getter

Getter 完全等同于 store 的 state 的计算值(computed value)。推荐使用箭头函数,并且它将接收 state 作为第一个参数。在使用常规函数定义 getter 时,我们也可以通过 this 访问到整个 store 实例,从而访问其他 getter。

你可以访问其他 store 的 getter:

1
2
3
4
5
6
7
8
9
10
11
12
13
import { useOtherStore } from './other-store';

export const useStore = defineStore('main', {
state: () => ({
// ...
}),
getters: {
otherGetter(state) {
const otherStore = useOtherStore();
return state.localData + otherStore.data;
}
}
});

Action

Action 相当于组件中的 method,它们定义了业务逻辑。action 也可通过 this 访问整个 store 实例。action 也可以是异步的,可以像函数或方法一样被调用,也可以在另一个 store 的 action 中被调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { useAuthStore } from './auth-store';

export const useSettingsStore = defineStore('settings', {
state: () => ({
preferences: null
// ...
}),
actions: {
async fetchUserPreferences() {
const auth = useAuthStore();
if (auth.isAuthenticated) {
this.preferences = await fetchPreferences();
} else {
throw new Error('User must be authenticated');
}
}
}
});

你可以通过 store.$onAction() 来监听 action 和他们的结果。传递给它的回调函数会在 action 本身之前执行。after 允许在 promise 解决之后执行回调函数。onError 允许在 action 抛出错误或 reject 时执行回调函数。

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
const unsubscribe = someStore.$onAction(
({
name, // action 名称
store, // store 实例,类似 `someStore`
args, // 传递给 action 的参数数组
after, // 在 action 返回或解决后的钩子
onError // action 抛出或拒绝的钩子
}) => {
// 为这个特定的 action 调用提供一个共享变量
const startTime = Date.now();
// 这将在执行 "store "的 action 之前触发。
console.log(`Start "${name}" with params [${args.join(', ')}].`);

// 这将在 action 成功并完全运行后触发。
// 它等待着任何返回的 promise
after(result => {
console.log(`Finished "${name}" after ${Date.now() - startTime}ms.\nResult: ${result}.`);
});

// 如果 action 抛出或返回一个拒绝的 promise,这将触发
onError(error => {
console.warn(`Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`);
});
}
);

// 手动删除监听器
unsubscribe();

Pinia 插件

Pinia 支持通过 pinia.use() 添加插件,Pinia 插件是一个函数,可以选择性地返回要添加到 store 的属性。它接收一个可选参数,即 context:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { createPinia } from 'pinia';

// 创建的每个 store 中都会添加一个名为 `secret` 的属性。
// 在安装此插件后,插件可以保存在不同的文件中
function SecretPiniaPlugin(context) {
// context.pinia // 用 `createPinia()` 创建的 pinia。
// context.app // 用 `createApp()` 创建的当前应用(仅 Vue 3)。
// context.store // 该插件想扩展的 store
// context.options // 定义传给 `defineStore()` 的 store 的可选对象。
return { secret: 'the cake is a lie' };
}

const pinia = createPinia();
// 将该插件交给 Pinia
pinia.use(SecretPiniaPlugin);

// 在另一个文件中
const store = useStore();
store.secret; // 'the cake is a lie'

以下为插件可扩展的内容:

  • 为 store 添加新的属性
  • 定义 store 时增加新的选项
  • 为 store 增加新的方法
  • 包装现有的方法
  • 改变甚至取消 action
  • 实现副作用,如本地存储
  • 仅应用插件于特定 store

当添加外部属性、第三方库的类实例或非响应式的简单值时,你应该先用 markRaw() 来包装一下它,再将它传给 pinia。下面是一个在每个 store 中添加路由器的例子:

1
2
3
4
5
6
7
import { markRaw } from 'vue';
// 根据你的路由器的位置来调整
import { router } from './router';

pinia.use(({ store }) => {
store.router = markRaw(router);
});

Pinia 与 Vuex 区别

Pinia 是 Vue3 推荐的状态管理库,而 Vuex 将不再更迭,从事件顺序上看,Pinia 可以看做是 Vuex5 。

  1. Pinia 提供了更简单的 API,也提供了符合组合式 API 风格的 API,搭配 Typescript 一起使用时有可靠的类型推断支持。
  2. Pinia API 已经稳定,新功能需要经过 RFC 流程。Vuex 不再更新。
  3. Vuex3.x 只适配 Vue2,Vuex 4.x 适配 Vue3, Pinia 适配 Vue3 和 Vue2。
  4. Pinia 没有 mutation,Vuex 中使用 mutation 记录数据的更新。
    Pinia 在 action 执行完成后会自动发布给订阅者,所以不需要 mutation。
  5. Pinia 无需要创建自定义的复杂包装器来支持 TypeScript。
  6. Pinia 无过多的魔法字符串注入,只需要导入函数并调用它们。
  7. Pinia 无需动态添加 Store,默认即是动态的。
  8. Pinia 不再有嵌套结构的模块,提供扁平的 Store 结构。
  9. Pinia 不再有可命名的模块。