目录
搭建pinia环境
存储数据
组件中使用数据
修改数据
storeToRefs
$subscribe
pinia相当于vue2中的vuex,pinia也是vue.js状态管理库。
下载
npm install pinia
创建
src/main.js
import { createApp } from 'vue'
import App from './App.vue'
/* 引入createPinia,用于创建pinia */
import { createPinia } from 'pinia'
/* 创建pinia */
const pinia = createPinia()
const app = createApp(App)
/* 使用插件 */
app.use(pinia)
app.mount('#app')
它有三个概念:store、getters、actions,相当于组件中的data、computed和methods。
src/store/count.js
// 引入defineStore用于创建store
import {defineStore} from 'pinia'
// 定义并暴露一个store
export const useCountStore = defineStore('count',{
// 动作
actions:{
increment(value) {
this.sum += value
}
},
// 状态
state(){
return {
sum:6,
a:1,
b:2,
c:3
}
},
// 计算
getters:{
bigSum:(state) => state.sum *10,
}
})
actions中可以通过this来获取到state中的数据,getters用于处理state中的数据。
state中的数据:{{ countStore.sum }}
getters处理的数据:{{ countStore.bigSum }}
(1)直接修改
countStore.sum = 666
(2)批量修改
countStore.$patch({
sum:999,
a:11,
b:22,
c:33
})
(3)通过actions修改,然后在组件中调用actions中的方法
使用storeToRefs可以将store中的数据转换成ref对象。
注意:pinia中的storeToRefs只会对数据本身转换,而vue中的toRef会转换store中的数据。
我们通过解构拿到的数据不是响应式的,所以需要使用storeToRefs将它们变成响应式的。
当前求和为:{{sum}}
使用$subscribe方法可以侦听store中的数据变化
countStore.$subscribe((mutate,state)=>{
console.log(mutate, state);
})