什么是Pinia
Pinia是Vue 的最新 状态管理工具 ,是Vuex 的替代品
-
提供更加简单的API (去掉了 mutation )
-
提供符合,组合式风格的API (和 Vue3 新语法统一)
-
去掉了 modules 的概念,每一个 store 都是一个独立的模块
-
配合 TypeScript 更加友好,提供可靠的类型推断
按官网的步骤配置

javascript
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形式返回
- 组件导入store中的定义方法,执行方法获取对象,并以 对象.xxx的形式使用数据和方法

javascript
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
// 定义store
// defineStore(仓库的唯一标识, () => { ... })
export const useCounterStore = defineStore('counter', () => {
// 声明数据 state - count
const count = ref(100)
// 声明操作数据的方法 action (普通函数)
const addCount = () => count.value++
const subCount = () => count.value--
// 声明基于数据派生的计算属性 getters (computed)
const double = computed(() => count.value * 2)
// 声明数据 state - msg
const msg = ref('hello pinia')
return {
count,
double,
addCount,
subCount,
msg,
}
})
注意组件导入时一般是不能以结构形式导入store里的数据的,会使数据丢失响应式
javascript
// 此时,直接解构,不处理,数据会丢失响应式
const { count, msg } = counterStore
但我们可以使用storeToRefs函数可以辅助保持数据(state + getter)的响应式解构
javascript
import { storeToRefs } from 'pinia'
javascript
const { count, name } = storeToRefs(counterStore)
但是方法不是响应式数据因此可以直接结构传递
javascript
const { getList } = channelStore
Pinia持久化插件
pinia-plugin-persistedstate可以让我们store中的数据持久化(存储在本地存储中)
具体可查看官方文档:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/
使用流程
- 安装插件
javascript
npm i pinia-plugin-persistedstate
- main.js导入
javascript
import persist from 'pinia-plugin-persistedstate'
3.绑定在Pinia实例上
javascript
const pinia = createPinia() // 创建Pinia实例
const app = createApp(App) // 创建根实例
app.use(pinia.use(persist)) // pinia插件的安装配置
- store仓库中,persist: true(默认情况,其他配置看官网)开启
javascript
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
// 定义store
// defineStore(仓库的唯一标识, () => { ... })
export const useCounterStore = defineStore('counter', () => {
// 声明数据 state - count
const count = ref(100)
// 声明操作数据的方法 action (普通函数)
const addCount = () => count.value++
const subCount = () => count.value--
// 声明基于数据派生的计算属性 getters (computed)
const double = computed(() => count.value * 2)
// 声明数据 state - msg
const msg = ref('hello pinia')
return {
count,
double,
addCount,
subCount,
msg,
}
}, {
// persist: true // 开启当前模块的持久化
persist: {
key: 'hm-counter', // 修改本地存储的唯一标识
paths: ['count'] // 存储的是哪些数据
}
})
Pinia和Veux的不同
