pinia-vue3状态管理工具


*前言

  • Pinia ,发音为 /piːnjʌ/,来源于西班牙语 piña 。意思为菠萝,表示与菠萝一样,由很多小块组成。在 Pinia 中,每个 Store 都是单独存在,一同进行状态管理。
  • Pinia 是由 Vue.js 团队成员开发,最初是为了探索 Vuex 下一次迭代会是什么样子。过程中,Pinia 实现了 Vuex5 提案的大部分内容,于是就取而代之了。
  • 与 Vuex 相比,Pinia 提供了更简单的 API,更少的规范,以及 Composition-API 风格的 API 。更重要的是,与 TypeScript 一起使用具有可靠的类型推断支持。

*Pinia 与 Vuex 3.x/4.x 的不同

  • mutations 不复存在。只有 state 、getters 、actions。
  • actions 中支持同步和异步方法修改 state 状态。
  • 与 TypeScript 一起使用具有可靠的类型推断支持。
  • 不再有模块嵌套,只有 Store 的概念,Store 之间可以相互调用。
  • 支持插件扩展,可以非常方便实现本地存储等功能。
  • 更加轻量,压缩后体积只有 2kb 左右。

*基本用法

1. 安装

npm install pinia

2. 引入
// src/store/index.ts
import { createPinia } from "pinia";
import type { App } from "vue";
const pinia = createPinia()
export default function registerPinia(vue:App<Element>){
    vue.use(pinia)
}


//main.ts
import { createApp } from 'vue'
import registerPinia from './pinia'
import App from './App.vue'
const vue = createApp(App)
registerPinia(vue)
vue.mount('#app')

3. 使用

src/stores/modules 目录下创建 counter.js 文件,使用 defineStore() 定义一个 Store 。defineStore() 第一个参数是 storeId ,第二个参数是一个选项对象:

// src/stores/modules/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    doubleCount: (state) => state.count * 2
  },
  actions: {
    increment() {
      this.count++
    }
  }
})

我们也可以使用更高级的方法,第二个参数传入一个函数来定义 Store :

// src/stores/modules/counter.js
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, doubleCount, increment }
})

在组件中使用 :

<script setup>
import { useCounterStore } from '@/stores/counter'

const counterStore = useCounterStore()
// 以下三种方式都会被 devtools 跟踪
counterStore.count++
counterStore.$patch({ count: counterStore.count + 1 })
counterStore.increment()
</script>

<template>
  <div>{{ counterStore.count }}</div>
  <div>{{ counterStore.doubleCount }}</div>
</template>

下面介绍各个模块的功能与用法

*state

1. 解构

store 是一个用 reactive 包裹的对象,如果直接解构会失去响应性。我们可以使用 storeToRefs() 对其进行解构:

<script setup>
import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/stores/counter'

const counterStore = useCounterStore()
const { count, doubleCount } = storeToRefs(counterStore)
</script>

<template>
  <div>{{ count }}</div>
  <div>{{ doubleCount }}</div>
</template>

2. 修改

除了可以直接用 store.count++ 来修改 store,我们还可以调用 p a t c h 方法进行修改。 patch 方法进行修改。 patch方法进行修改。patch 性能更高,并且可以同时修改多个状态:

<script setup>
import { useCounterStore } from '@/stores/counter'

const counterStore = useCounterStore()
counterStore.$patch({
  count: counterStore.count + 1,
  name: 'Abalam',
})
</script>

但是,这种方法修改集合(比如从数组中添加、删除、插入元素)都需要创建一个新的集合,代价太高。因此,$patch 方法也接受一个函数来批量修改:

cartStore.$patch((state) => {
  state.items.push({ name: 'shoes', quantity: 1 })
  state.hasChanged = true
})

3. 监听

我们可以通过 $subscribe() 方法可以监听 store 状态的变化,类似于 Vuex 的 subscribe 方法。与 watch() 相比,使用 $subscribe() 的优点是,store 多个状态发生变化之后,回调函数只会执行一次:

<script setup>
import { useCounterStore } from '@/stores/counter'

const counterStore = useCounterStore()
counterStore.$subscribe((mutation, state) => {
  // 每当状态发生变化时,将 state 持久化到本地存储
  localStorage.setItem('counter', JSON.stringify(state))
})
</script>

也可以监听 pinia 实例上所有 store 的变化

// src/main.js
import { watch } from 'vue'
import { createPinia } from 'pinia'

const pinia = createPinia()
watch(
  pinia.state,
  (state) => {
    // 每当状态发生变化时,将所有 state 持久化到本地存储
    localStorage.setItem('piniaState', JSON.stringify(state))
  },
  { deep: true }
)

*Getters

1. 访问 store 实例

大多数情况下,getter 只会依赖 state 状态。但有时候,它会使用到其他的 getter ,这时候我们可以通过 this 访问到当前 store 实例。

// src/stores/modules/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    doubleCount(state) {
      return state.count * 2
    },
    doublePlusOne() {
      return this.doubleCount + 1
    }
  }
})

2. 访问其他 store 的getter

要使用其他 Store 的 getter,可以直接在 getter 内部使用:

// src/stores/modules/counter.js
import { defineStore } from 'pinia'
import { useOtherStore } from './otherStore'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 1
  }),
  getters: {
    composeGetter(state) {
      const otherStore = useOtherStore()
      return state.count + otherStore.count
    }
  }
})

3. 将参数传递给getter

getter 本质上是一个 computed ,无法向它传递任何参数。但是,我们可以让它返回一个函数以接受参数:

// src/stores/modules/user.js
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    users: [{ id: 1, name: 'Tom'}, {id: 2, name: 'Jack'}]
  }),
  getters: {
    getUserById: (state) => {
      return (userId) => state.users.find((user) => user.id === userId)
    }
  }
})

在组件中使用:

<script setup>
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const { getUserById } = storeToRefs(userStore)
</script>

<template>
  <p>User: {{ getUserById(2) }}</p>
</template>

*Actions

1. 访问store实例

与 getters 一样,actions 可以通过 this 访问当 store 的实例。不同的是,actions 可以是异步的:

// src/stores/modules/user.js
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({ userData: null }),
  actions: {
    async registerUser(login, password) {
      try {
        this.userData = await api.post({ login, password })
      } catch (error) {
        return error
      }
    }
  }
})

2. 访问其他store的action

要使用其他 Store 的 action,也可以直接在 action 内部使用:

// src/stores/modules/setting.js
import { defineStore } from 'pinia'
import { useAuthStore } from './authStore'

export const useSettingStore = defineStore('setting', {
  state: () => ({ preferences: null }),
  actions: {
    async fetchUserPreferences(preferences) {
      const authStore = useAuthStore()
      if (authStore.isAuthenticated()) {
        this.preferences = await fetchPreferences()
      } else {
        throw new Error('User must be authenticated!')
      }
    }
  }
})

*Plugins

由于是底层 API,Pania Store 完全支持扩展。以下是可以扩展的功能列表:

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

下面介绍pania非常好用的,也是我经常使用的一款插件,它可以自主实现本地持久化存储:

实现本地存储
  1. 安装

npm i pinia-plugin-persist

  1. 引入
// src/store/index.ts
import { createPinia } from "pinia";
import type { App } from "vue";
import piniaPluginPersist from 'pinia-plugin-persist'
const pinia = createPinia()
pinia.use(piniaPluginPersist)
export default function registerPinia(vue:App<Element>){
    vue.use(pinia)
}
// src/store/modules/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 1 }),
  // 开启数据缓存
  persist: {
    enabled: true
  }
})

默认情况下,会以 storeId 作为 key 值,把 state 中的所有状态存储在 sessionStorage 中。我们也可以通过 strategies 进行修改:

// 开启数据缓存
persist: {
  enabled: truestrategies: [
    {
      key: 'myCounter', // 存储的 key 值,默认为 storeId
      storage: localStorage, // 存储的位置,默认为 sessionStorage
      paths: ['name', 'age'], // 需要存储的 state 状态,默认存储所有的状态
    }
  ]
}

更多参数设置可参考:
persist

参考文档:pania 中文文档

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值