官方文档
Pinia :::success Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。 :::
特点:
完整的 ts 的支持 足够轻量,压缩后的体积只有1kb左右 去除 mutations,只有 state,getters,actions actions 支持同步和异步 代码扁平化没有模块嵌套,只有 store 的概念,store 之间可以自由使用,每一个store都是独立的 无需手动添加 store,store 一旦创建便会自动添加 支持Vue3 和 Vue2
起步:
1、安装
yarn add pinia# or with npmnpm install pinia
2、引入pinia
// Vue3 main.tsimport { createApp } from 'vue'import App from './App.vue'import {createPinia} from 'pinia'const pinia = createPinia()let app = createApp(App)app.use(pinia)app.mount('#app')
如果您使用的是 Vue 2,您还需要安装一个插件并pinia在应用程序的根目录注入创建的插件:
//Vue2 使用import { createPinia, PiniaVuePlugin } from 'pinia'Vue.use(PiniaVuePlugin)const pinia = createPinia()new Vue({el: '#app',// other options...// ...// note the same `pinia` instance can be used across multiple Vue apps on// the same pagepinia,})
使用
1、基础使用
import { defineStore } from 'pinia'import {Names} from './store-name'export const useTestStore = defineStore(Names.TEST, {state: () => ({name: 'pika',age: 18}),// computed 可以修饰一些值getters: {},// methods 可以做同步和异步的操作,提交stateactions: {}})
// 这里使用枚举,包裹store的命名export const enum Names {TEST = 'TEST'}
<script setup lang="ts">import {useTestStore} from './store'const Test = useTestStore()</script><template><span>这里使用了pinia:</span><div>{{Test.name}}--{{Test.age}}</div></template><style lang="less" scoped></style>
2、state
我们可以采取不同的方式对store中的state进行修改
<script setup lang="ts">import {useTestStore} from './store'const Test = useTestStore()// 进行state的修改const change = () => {// 第一种方式,可以直接修改属性的state的值Test.age++// 第二种方式,在$patch中修改状态的值Test.$patch({name: 'xixi',age: 22})// 第三种方式 在$patch中接收工厂函数Test.$patch((state)=>{state.name = 'xixi'state.age = 30})// 第四种方式 在$state中修改整个状态(所有的值)Test.$state = {name: 'xixi',age: 60}// 第五种方式, 直接调用action里定义的函数修改状态Test.setName("lala")}</script><template><span>这里使用了pinia:</span><div>{{Test.name}}--{{Test.age}}</div><button @click="change">change</button></template><style lang="less" scoped></style>
import { defineStore } from 'pinia'import { Names } from './store-name'export const useTestStore = defineStore(Names.TEST, {state: () => ({name: 'pika',age: 18}),// computed 可以修饰一些值getters: {},// methods 可以做同步和异步的操作,提交stateactions: {setName(name:string) {this.name = name}}})
3、解构store
在Pinia是不允许直接解构是会失去响应性的。 为此需要借助于pinia里的storeToRefs
<script setup lang="ts">import { storeToRefs } from 'pinia';import {useTestStore} from './store'const Test = useTestStore()// 解构store// 注意!! 在pinia中解构是不具有响应式的,// 为此我们需要借助pinia的api--> storeToRefs()// storeToRefs先将store去外壳toRaw转为对象,之后遍历store的key,// 对于state的key包上toRef,使得state是有响应的// 下面的storeToRefs取自vue3源码// function storeToRefs(store) {// // See https://github.com/vuejs/pinia/issues/852// // It's easier to just use toRefs() even if it includes more stuff// if (isVue2) {// // @ts-expect-error: toRefs include methods and others// return toRefs(store);// }// else {// store = toRaw(store);// const refs = {};// for (const key in store) {// const value = store[key];// if (isRef(value) || isReactive(value)) {// // @ts-expect-error: the key is state or getter// refs[key] =// // ---// toRef(store, key);// }// }// return refs;// }// }const { name, age } = storeToRefs(Test)// 进行state的修改const change = () => {// console.log(name, "@@@", age)// Test.age++age.value++}</script><template><span>这里使用了pinia:</span><div>Initial Value: {{Test.name}}--{{Test.age}}</div><div>new Value: {{name}}--{{age}}</div><button @click="change">change</button></template><style lang="less" scoped></style>
4、actions和getters
有2种情况的,分同步和异步: 同步其实就是类似上面的写法,下面列出异步的写法
import { defineStore } from 'pinia'import { Names } from './store-name'type User = {name: string,age: number}// 这里设置一个change之后的user// 同步写法// const Runner:User = {// name:'xixi',// age: 20// }// 下面模拟实现异步修改stateconst Login = (): Promise<User> => {return new Promise((resolve) => {setTimeout(() => {resolve({name: 'xixi',age: 20})}, 2000)})}export const useTestStore = defineStore(Names.TEST, {state: () => ({user: <User>{name: 'pika',age: 18}}),// computed 可以修饰一些值getters: {},// methods 可以做同步和异步的操作,提交stateactions: {//同步写法// setUser() {// this.user = Runner// }// 异步actionasync setUser() {let result = await Login()this.user = result}}})
actions和getters中也可以相互调用,见下面例子
import { defineStore } from 'pinia'import { Names } from './store-name'type User = {name: string,age: number}// 这里设置一个change之后的user// 同步写法// const Runner:User = {// name:'xixi',// age: 20// }// 下面模拟实现异步修改stateconst Login = (): Promise<User> => {return new Promise((resolve) => {setTimeout(() => {resolve({name: 'xixi',age: 20})}, 2000)})}export const useTestStore = defineStore(Names.TEST, {state: () => ({user: <User>{name: 'pika',age: 18},name: 'Heisenberg'}),// computed 可以修饰一些值getters: {newName():string {return `${this.name}-${this.getUserAge}`},getUserAge():number {return this.user.age}},// methods 可以做同步和异步的操作,提交stateactions: {//同步写法// setUser() {// this.user = Runner// }// 异步actionasync setUser() {let result = await Login()this.user = resultthis.setName('WW')},setName(name:string) {this.name = name}}})
5、实例上的api
1、$reset()
可以通过调用 store 上的 $reset() 方法将状态 重置 到其初始值
const reset = () => {// $reset()恢复state的值store.$reset()}
2、$subscribe()
:::warning 可以通过 store 的 $subscribe() 方法查看状态及其变化,类似于 Vuex 的 subscribe 方法。 与常规的 watch() 相比,使用 $subscribe() 的优点是 subscriptions 只会在 patches 之后触发一次。 :::
store.$subscribe((args, state) => {console.log('args:', args)console.log("state:", state)}, {detached:true, //和$onAction()的第二个参数设置为true的效果是一样的deep:true,flush:'post'})
3、$onAction()
:::danger
可以使用 store.$onAction() 订阅 action 及其结果。 传递给它的回调在 action 之前执行。 after 处理 Promise 并允许您在 action 完成后执行函数。 以类似的方式,onError 允许您在处理中抛出错误。 这些对于在运行时跟踪错误很有用,类似于 Vue 文档中的这个提示。
默认情况下,action subscriptions 绑定到添加它们的组件(如果 store 位于组件的 setup() 内)。 意思是,当组件被卸载时,它们将被自动删除。 如果要在卸载组件后保留它们,请将 true 作为第二个参数传递给当前组件的 detachaction subscription.
例如: someStore.$onAction(callback, true) // 此订阅将在组件卸载后保留
:::
const unsubscribe = someStore.$onAction(({name, // action 的名字store, // store 实例args, // 调用这个 action 的参数after, // 在这个 action 执行完毕之后,执行这个函数onError, // 在这个 action 抛出异常的时候,执行这个函数}) => {// 记录开始的时间变量const startTime = Date.now()// 这将在 `store` 上的操作执行之前触发console.log(`Start "${name}" with params [${args.join(', ')}].`)// 如果 action 成功并且完全运行后,after 将触发。// 它将等待任何返回的 promiseafter((result) => {console.log(`Finished "${name}" after ${Date.now() - startTime}ms.\nResult: ${result}.`)})// 如果 action 抛出或返回 Promise.reject ,onError 将触发onError((error) => {console.warn(`Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`)})})// 手动移除订阅unsubscribe()
6、插件
由于是底层 API,Pania Store可以完全扩展。 以下是您可以执行的操作列表:
- 向 Store 添加新属性
- 定义 Store 时添加新选项
- 为 Store 添加新方法
- 包装现有方法
- 更改甚至取消操作
- 实现本地存储等副作用
仅适用于特定 Store
使用 pinia.use() 将插件添加到 pinia 实例中。
import { createPinia } from 'pinia'// 为安装此插件后创建的每个store添加一个名为 `secret` 的属性// 这可能在不同的文件中function SecretPiniaPlugin() {return { secret: 'the cake is a lie' }}const pinia = createPinia()// 将插件提供给 piniapinia.use(SecretPiniaPlugin)// 在另一个文件中const store = useStore()store.secret // 'the cake is a lie'
实现pinia的一个插件用于页面的缓存
pinia小插件 :::warning pinia 和 vuex 都有一个通病 页面刷新状态会丢失。这里使用一个插件来缓存state :::
import { createApp } from 'vue'import App from './App.vue'import { createPinia, PiniaPluginContext } from 'pinia'// 设置类型别名type Options = {key?: string}// 设置一个默认的key,用于当key没有传的时候const __piniaKey__: string = 'piniaKey'// 定义获取state的函数const getStorage = (key: string) => {// 因为会报错:‘不能将类型nuLl分配给类型string’ 这里需要断言下为string, 因为三目运算符也已经判断过了return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : {}}// 定义存储state的函数const setStorage = (key: string, value: any) => {// 这里value存储成字符串的形式localStorage.setItem(key, JSON.stringify(value))}// 在main.ts中定义插件const piniaPlugin = (options: Options) => {// 函数柯里化return (context: PiniaPluginContext) => {// 解构赋值出storeconst { store } = contextconst data = getStorage(`${options?.key ?? __piniaKey__}-${store.$id} `)console.log(data)// store订阅状态store.$subscribe(() => {// 注意,这里store.$state是一个代理的对象,需要用toRaw()来转为原始对象setStorage(`${options?.key ?? __piniaKey__}-${store.$id} `, toRaw(store.$state))})// 这里将getStorage获取到的本地state值直接赋予渲染好的页面return { ...data }}}const pinia = createPinia()// 注册pinia的插件// 这里的piniaPlugin是pinia帮我们调用的,pinia.use(piniaPlugin({key: 'pinia'}))const app = createApp(App)app.use(pinia)app.mount('#app')
