官方文档

Pinia :::success Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。 :::

特点:

完整的 ts 的支持 足够轻量,压缩后的体积只有1kb左右 去除 mutations,只有 state,getters,actions actions 支持同步和异步 代码扁平化没有模块嵌套,只有 store 的概念,store 之间可以自由使用,每一个store都是独立的 无需手动添加 store,store 一旦创建便会自动添加 支持Vue3 和 Vue2

起步:

1、安装

  1. yarn add pinia
  2. # or with npm
  3. npm install pinia

2、引入pinia

  1. // Vue3 main.ts
  2. import { createApp } from 'vue'
  3. import App from './App.vue'
  4. import {createPinia} from 'pinia'
  5. const pinia = createPinia()
  6. let app = createApp(App)
  7. app.use(pinia)
  8. app.mount('#app')

如果您使用的是 Vue 2,您还需要安装一个插件并pinia在应用程序的根目录注入创建的插件:

  1. //Vue2 使用
  2. import { createPinia, PiniaVuePlugin } from 'pinia'
  3. Vue.use(PiniaVuePlugin)
  4. const pinia = createPinia()
  5. new Vue({
  6. el: '#app',
  7. // other options...
  8. // ...
  9. // note the same `pinia` instance can be used across multiple Vue apps on
  10. // the same page
  11. pinia,
  12. })

使用

图片.png

1、基础使用

  1. import { defineStore } from 'pinia'
  2. import {Names} from './store-name'
  3. export const useTestStore = defineStore(Names.TEST, {
  4. state: () => ({
  5. name: 'pika',
  6. age: 18
  7. }),
  8. // computed 可以修饰一些值
  9. getters: {
  10. },
  11. // methods 可以做同步和异步的操作,提交state
  12. actions: {
  13. }
  14. })
  1. // 这里使用枚举,包裹store的命名
  2. export const enum Names {
  3. TEST = 'TEST'
  4. }
  1. <script setup lang="ts">
  2. import {useTestStore} from './store'
  3. const Test = useTestStore()
  4. </script>
  5. <template>
  6. <span>这里使用了pinia:</span>
  7. <div>
  8. {{Test.name}}--{{Test.age}}
  9. </div>
  10. </template>
  11. <style lang="less" scoped>
  12. </style>

2、state

我们可以采取不同的方式对store中的state进行修改

  1. <script setup lang="ts">
  2. import {useTestStore} from './store'
  3. const Test = useTestStore()
  4. // 进行state的修改
  5. const change = () => {
  6. // 第一种方式,可以直接修改属性的state的值
  7. Test.age++
  8. // 第二种方式,在$patch中修改状态的值
  9. Test.$patch({
  10. name: 'xixi',
  11. age: 22
  12. })
  13. // 第三种方式 在$patch中接收工厂函数
  14. Test.$patch((state)=>{
  15. state.name = 'xixi'
  16. state.age = 30
  17. })
  18. // 第四种方式 在$state中修改整个状态(所有的值)
  19. Test.$state = {
  20. name: 'xixi',
  21. age: 60
  22. }
  23. // 第五种方式, 直接调用action里定义的函数修改状态
  24. Test.setName("lala")
  25. }
  26. </script>
  27. <template>
  28. <span>这里使用了pinia:</span>
  29. <div>
  30. {{Test.name}}--{{Test.age}}
  31. </div>
  32. <button @click="change">change</button>
  33. </template>
  34. <style lang="less" scoped>
  35. </style>
  1. import { defineStore } from 'pinia'
  2. import { Names } from './store-name'
  3. export const useTestStore = defineStore(Names.TEST, {
  4. state: () => ({
  5. name: 'pika',
  6. age: 18
  7. }),
  8. // computed 可以修饰一些值
  9. getters: {
  10. },
  11. // methods 可以做同步和异步的操作,提交state
  12. actions: {
  13. setName(name:string) {
  14. this.name = name
  15. }
  16. }
  17. })

3、解构store

在Pinia是不允许直接解构是会失去响应性的。 为此需要借助于pinia里的storeToRefs

  1. <script setup lang="ts">
  2. import { storeToRefs } from 'pinia';
  3. import {useTestStore} from './store'
  4. const Test = useTestStore()
  5. // 解构store
  6. // 注意!! 在pinia中解构是不具有响应式的,
  7. // 为此我们需要借助pinia的api--> storeToRefs()
  8. // storeToRefs先将store去外壳toRaw转为对象,之后遍历store的key,
  9. // 对于state的key包上toRef,使得state是有响应的
  10. // 下面的storeToRefs取自vue3源码
  11. // function storeToRefs(store) {
  12. // // See https://github.com/vuejs/pinia/issues/852
  13. // // It's easier to just use toRefs() even if it includes more stuff
  14. // if (isVue2) {
  15. // // @ts-expect-error: toRefs include methods and others
  16. // return toRefs(store);
  17. // }
  18. // else {
  19. // store = toRaw(store);
  20. // const refs = {};
  21. // for (const key in store) {
  22. // const value = store[key];
  23. // if (isRef(value) || isReactive(value)) {
  24. // // @ts-expect-error: the key is state or getter
  25. // refs[key] =
  26. // // ---
  27. // toRef(store, key);
  28. // }
  29. // }
  30. // return refs;
  31. // }
  32. // }
  33. const { name, age } = storeToRefs(Test)
  34. // 进行state的修改
  35. const change = () => {
  36. // console.log(name, "@@@", age)
  37. // Test.age++
  38. age.value++
  39. }
  40. </script>
  41. <template>
  42. <span>这里使用了pinia:</span>
  43. <div>Initial Value: {{Test.name}}--{{Test.age}}</div>
  44. <div>new Value: {{name}}--{{age}}</div>
  45. <button @click="change">change</button>
  46. </template>
  47. <style lang="less" scoped>
  48. </style>

4、actions和getters

有2种情况的,分同步和异步: 同步其实就是类似上面的写法,下面列出异步的写法

  1. import { defineStore } from 'pinia'
  2. import { Names } from './store-name'
  3. type User = {
  4. name: string,
  5. age: number
  6. }
  7. // 这里设置一个change之后的user
  8. // 同步写法
  9. // const Runner:User = {
  10. // name:'xixi',
  11. // age: 20
  12. // }
  13. // 下面模拟实现异步修改state
  14. const Login = (): Promise<User> => {
  15. return new Promise((resolve) => {
  16. setTimeout(() => {
  17. resolve({
  18. name: 'xixi',
  19. age: 20
  20. })
  21. }, 2000)
  22. })
  23. }
  24. export const useTestStore = defineStore(Names.TEST, {
  25. state: () => ({
  26. user: <User>{
  27. name: 'pika',
  28. age: 18
  29. }
  30. }),
  31. // computed 可以修饰一些值
  32. getters: {
  33. },
  34. // methods 可以做同步和异步的操作,提交state
  35. actions: {
  36. //同步写法
  37. // setUser() {
  38. // this.user = Runner
  39. // }
  40. // 异步action
  41. async setUser() {
  42. let result = await Login()
  43. this.user = result
  44. }
  45. }
  46. })

actions和getters中也可以相互调用,见下面例子

  1. import { defineStore } from 'pinia'
  2. import { Names } from './store-name'
  3. type User = {
  4. name: string,
  5. age: number
  6. }
  7. // 这里设置一个change之后的user
  8. // 同步写法
  9. // const Runner:User = {
  10. // name:'xixi',
  11. // age: 20
  12. // }
  13. // 下面模拟实现异步修改state
  14. const Login = (): Promise<User> => {
  15. return new Promise((resolve) => {
  16. setTimeout(() => {
  17. resolve({
  18. name: 'xixi',
  19. age: 20
  20. })
  21. }, 2000)
  22. })
  23. }
  24. export const useTestStore = defineStore(Names.TEST, {
  25. state: () => ({
  26. user: <User>{
  27. name: 'pika',
  28. age: 18
  29. },
  30. name: 'Heisenberg'
  31. }),
  32. // computed 可以修饰一些值
  33. getters: {
  34. newName():string {
  35. return `${this.name}-${this.getUserAge}`
  36. },
  37. getUserAge():number {
  38. return this.user.age
  39. }
  40. },
  41. // methods 可以做同步和异步的操作,提交state
  42. actions: {
  43. //同步写法
  44. // setUser() {
  45. // this.user = Runner
  46. // }
  47. // 异步action
  48. async setUser() {
  49. let result = await Login()
  50. this.user = result
  51. this.setName('WW')
  52. },
  53. setName(name:string) {
  54. this.name = name
  55. }
  56. }
  57. })

5、实例上的api

1、$reset()

可以通过调用 store 上的 $reset() 方法将状态 重置 到其初始值

  1. const reset = () => {
  2. // $reset()恢复state的值
  3. store.$reset()
  4. }

2、$subscribe()

:::warning 可以通过 store 的 $subscribe() 方法查看状态及其变化,类似于 Vuex 的 subscribe 方法。 与常规的 watch() 相比,使用 $subscribe() 的优点是 subscriptions 只会在 patches 之后触发一次。 :::

  1. store.$subscribe((args, state) => {
  2. console.log('args:', args)
  3. console.log("state:", state)
  4. }, {
  5. detached:true, //和$onAction()的第二个参数设置为true的效果是一样的
  6. deep:true,
  7. flush:'post'
  8. })

图片.png

3、$onAction()

:::danger 可以使用 store.$onAction() 订阅 action 及其结果。 传递给它的回调在 action 之前执行。 after 处理 Promise 并允许您在 action 完成后执行函数。 以类似的方式,onError 允许您在处理中抛出错误。 这些对于在运行时跟踪错误很有用,类似于 Vue 文档中的这个提示。
默认情况下,action subscriptions 绑定到添加它们的组件(如果 store 位于组件的 setup() 内)。 意思是,当组件被卸载时,它们将被自动删除。 如果要在卸载组件后保留它们,请将 true 作为第二个参数传递给当前组件的 detachaction subscription.
例如: someStore.$onAction(callback, true) // 此订阅将在组件卸载后保留
:::

  1. const unsubscribe = someStore.$onAction(
  2. ({
  3. name, // action 的名字
  4. store, // store 实例
  5. args, // 调用这个 action 的参数
  6. after, // 在这个 action 执行完毕之后,执行这个函数
  7. onError, // 在这个 action 抛出异常的时候,执行这个函数
  8. }) => {
  9. // 记录开始的时间变量
  10. const startTime = Date.now()
  11. // 这将在 `store` 上的操作执行之前触发
  12. console.log(`Start "${name}" with params [${args.join(', ')}].`)
  13. // 如果 action 成功并且完全运行后,after 将触发。
  14. // 它将等待任何返回的 promise
  15. after((result) => {
  16. console.log(
  17. `Finished "${name}" after ${
  18. Date.now() - startTime
  19. }ms.\nResult: ${result}.`
  20. )
  21. })
  22. // 如果 action 抛出或返回 Promise.reject ,onError 将触发
  23. onError((error) => {
  24. console.warn(
  25. `Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`
  26. )
  27. })
  28. }
  29. )
  30. // 手动移除订阅
  31. unsubscribe()

6、插件

由于是底层 API,Pania Store可以完全扩展。 以下是您可以执行的操作列表:

  • 向 Store 添加新属性
  • 定义 Store 时添加新选项
  • 为 Store 添加新方法
  • 包装现有方法
  • 更改甚至取消操作
  • 实现本地存储等副作用
  • 仅适用于特定 Store

    使用 pinia.use() 将插件添加到 pinia 实例中。

  1. import { createPinia } from 'pinia'
  2. // 为安装此插件后创建的每个store添加一个名为 `secret` 的属性
  3. // 这可能在不同的文件中
  4. function SecretPiniaPlugin() {
  5. return { secret: 'the cake is a lie' }
  6. }
  7. const pinia = createPinia()
  8. // 将插件提供给 pinia
  9. pinia.use(SecretPiniaPlugin)
  10. // 在另一个文件中
  11. const store = useStore()
  12. store.secret // 'the cake is a lie'

实现pinia的一个插件用于页面的缓存

pinia小插件 :::warning pinia 和 vuex 都有一个通病 页面刷新状态会丢失。这里使用一个插件来缓存state :::

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import { createPinia, PiniaPluginContext } from 'pinia'
  4. // 设置类型别名
  5. type Options = {
  6. key?: string
  7. }
  8. // 设置一个默认的key,用于当key没有传的时候
  9. const __piniaKey__: string = 'piniaKey'
  10. // 定义获取state的函数
  11. const getStorage = (key: string) => {
  12. // 因为会报错:‘不能将类型nuLl分配给类型string’ 这里需要断言下为string, 因为三目运算符也已经判断过了
  13. return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : {}
  14. }
  15. // 定义存储state的函数
  16. const setStorage = (key: string, value: any) => {
  17. // 这里value存储成字符串的形式
  18. localStorage.setItem(key, JSON.stringify(value))
  19. }
  20. // 在main.ts中定义插件
  21. const piniaPlugin = (options: Options) => {
  22. // 函数柯里化
  23. return (context: PiniaPluginContext) => {
  24. // 解构赋值出store
  25. const { store } = context
  26. const data = getStorage(`${options?.key ?? __piniaKey__}-${store.$id} `)
  27. console.log(data)
  28. // store订阅状态
  29. store.$subscribe(() => {
  30. // 注意,这里store.$state是一个代理的对象,需要用toRaw()来转为原始对象
  31. setStorage(`${options?.key ?? __piniaKey__}-${store.$id} `, toRaw(store.$state))
  32. })
  33. // 这里将getStorage获取到的本地state值直接赋予渲染好的页面
  34. return { ...data }
  35. }
  36. }
  37. const pinia = createPinia()
  38. // 注册pinia的插件
  39. // 这里的piniaPlugin是pinia帮我们调用的,
  40. pinia.use(piniaPlugin({
  41. key: 'pinia'
  42. }))
  43. const app = createApp(App)
  44. app.use(pinia)
  45. app.mount('#app')