VueX进阶Pinia
什么是Pinia
Pinia是Vue 的最新 状态管理工具 ,是Vuex 的替代品
1. 提供更加简单的API (去掉了 mutation )
2. 提供符合,组合式风格的API (和 Vue3 新语法统一)
3. 去掉了 modules 的概念,每一个 store 都是一个独立的模块
4. 配合 TypeScript 更加友好,提供可靠的类型推断
按官网的步骤配置
import { createApp } from 'vue'
import { createPinia } from 'pinia'
// 导入持久化的插件
import persist from 'pinia-plugin-persistedstate'import App from './App.vue'
const pinia = createPinia() // 创建Pinia实例
const app = createApp(App) // 创建根实例
app.use(pinia.use(persist)) // pinia插件的安装配置
app.mount('#app') // 视图的挂载
Pinia基础使用
1.定义store(以方法形式导出),只有state和actions板块,Pinia中的 getters 直接使用 computed函数进行模拟,mutations和actions合并在一起现在可以在action中直接进行异步操作并修改数据,不用像vuex里一样再提交给mutations,也不用再使用commit和dispatch命令 ,state和action定义完成后需要以return形式返回
2. 组件导入store中的定义方法,执行方法获取对象,并以 对象.xxx的形式使用数据和方法
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'// 定义store
// defineStore(仓库的唯一标识, () => { ... })
export const useCounterStore = defineStore('counter', () => {// 声明数据 state - countconst count = ref(100)// 声明操作数据的方法 action (普通函数)const addCount = () => count.value++const subCount = () => count.value--// 声明基于数据派生的计算属性 getters (computed)const double = computed(() => count.value * 2)// 声明数据 state - msgconst msg = ref('hello pinia')return {count,double,addCount,subCount,msg,}
})
注意组件导入时一般是不能以结构形式导入store里的数据的,会使数据丢失响应式
// 此时,直接解构,不处理,数据会丢失响应式
const { count, msg } = counterStore
但我们可以使用storeToRefs函数可以辅助保持数据(state + getter)的响应式解构
import { storeToRefs } from 'pinia'
const { count, name } = storeToRefs(counterStore)
但是方法不是响应式数据因此可以直接结构传递
const { getList } = channelStore
Pinia持久化插件
pinia-plugin-persistedstate可以让我们store中的数据持久化(存储在本地存储中)
具体可查看官方文档:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/
使用流程
1. 安装插件
npm i pinia-plugin-persistedstate
2. main.js导入
import persist from 'pinia-plugin-persistedstate'
3.绑定在Pinia实例上
const pinia = createPinia() // 创建Pinia实例
const app = createApp(App) // 创建根实例
app.use(pinia.use(persist)) // pinia插件的安装配置
4. store仓库中,persist: true(默认情况,其他配置看官网)开启
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'// 定义store
// defineStore(仓库的唯一标识, () => { ... })
export const useCounterStore = defineStore('counter', () => {// 声明数据 state - countconst count = ref(100)// 声明操作数据的方法 action (普通函数)const addCount = () => count.value++const subCount = () => count.value--// 声明基于数据派生的计算属性 getters (computed)const double = computed(() => count.value * 2)// 声明数据 state - msgconst msg = ref('hello pinia')return {count,double,addCount,subCount,msg,}
}, {// persist: true // 开启当前模块的持久化persist: {key: 'hm-counter', // 修改本地存储的唯一标识paths: ['count'] // 存储的是哪些数据}
})