目录
pinia相当于vue2中的vuex,pinia也是vue.js状态管理库。
搭建pinia环境
下载
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中的数据。
组件中使用数据
<template>
<h2>state中的数据:{
{ countStore.sum }}</h2>
<h2>getters处理的数据:{
{ countStore.bigSum }}</h2>
<button @click="add">点击加三</button>
</template>
<script setup name="Count">
// 引入对应的useXxxxxStore
import {useCountStore} from '@/store/count'
// 调用useXxxxxStore得到对应的store
const countStore = useCountStore()
const add = () => {
//调用actions中的方法
countStore.increment(3)
}
</script>
修改数据
(1)直接修改
countStore.sum = 666
(2)批量修改
countStore.$patch({
sum:999,
a:11,
b:22,
c:33
})
(3)通过actions修改,然后在组件中调用actions中的方法
storeToRefs
使用storeToRefs可以将store中的数据转换成ref对象。
注意:pinia中的storeToRefs只会对数据本身转换,而vue中的toRef会转换store中的数据。
我们通过解构拿到的数据不是响应式的,所以需要使用storeToRefs将它们变成响应式的。
<template>
<div class="count">
<h2>当前求和为:{
{sum}}</h2>
</div>
</template>
<script setup lang="ts" name="Count">
import { useCountStore } from '@/store/count'
/* 引入storeToRefs */
import { storeToRefs } from 'pinia'
/* 得到countStore */
const countStore = useCountStore()
/* 使用storeToRefs转换countStore,随后解构 */
const {sum} = storeToRefs(countStore)
</script>
$subscribe
使用$subscribe方法可以侦听store中的数据变化
countStore.$subscribe((mutate,state)=>{
console.log(mutate, state);
})