Pinia是Vue.js官方维护的一个状态管理库用于写组合式api
存值(初始化)
一共有两种写法,一种是类似于
选项式
的写法,另一种是组合式
的写法
属性 :
defineStore:
pinia的核心,创建一个状态管理器,接收两个参数,第一个参数指定唯一值(ID、标识
),第二个值接收一个对象(配置
)
state:
要管理或存放的数据
action:
注意事项:在这里边可以使用this
,this指向整个这个store
,可以直接拿到state定义的变量
getter:
注意事项:这里边也可以直接使用this
,也可以函数接收state
第一种(类似于选项式
的写法)
//example.ts
import{defineStore} from 'pinia'
export const useExampleStore = defineStore('example',{
state(){
return{
//要存放的数据
sum : 0
}
},
actions:{
increment(){
//此处的this是指向这个整个store的可以拿到state中存放的值
this.sum ++
}
},
getters:{
//getter有两种写法
bigSum(){
return this.sum*10
},
doubleSum:(state):number => state.sum*2
}
})
第二种写法(组合式api
写法)
//example.ts
import {defineStore} from 'pinia'
import {ref} from 'vue'
export const useExampleStore = defineStore('example',()=>{
//需要存放的数据,就和普通的Vue3定义变量一样
let sum = ref(0)
//方法
function increment(){
sum ++
}
})
取值
在需要用到状态管理的文件中引入我们写好的状态管理文件(example.ts),然后再使用.
和hooks
的用法差不多
//example.vue
<div>{{exampleStore.sum}}</div>
import { useExampleStore } from '@/store/example.ts'
let exampleStore = useExampleStore()
这个地方也可以通过
解构赋值
的方式引出来,但会失去响应式
,可以使用storeToRefs
,恢复响应式
//example.vue
<div>{{sum}}</div>
import { storeToRefs } from 'pinia';
import { useExampleStore } from '@/store/example.ts'
let exampleStore = useExampleStore()
let { sum } = storeToRefs(exampleStore)
修改值
不同于
VueX
需要调用在库中写好的方法来进行修改,Pinia
的数据,可以在页面中就像普通变量一样进行修改,也会同步到存储库里.
一共有三种
写法
第一种写法
//example.vue
<h1>{{sum}}</h1>
<button @click="add">+1</button>
import { useExampleStore } from '@/store/example.ts'
let exampleStore = useExampleStore()
function add (){
//如果没对sum进行解构
exampleStore.sum ++
//如果对sum进行了解构
sum.value++
}
第二种写法($patch
)注意第二种函数式写法会接受一个参数,参数内容包含整个store
//example.vue
<h1>{{sum}}</h1>
<button @click="add">+1</button>
import { useExampleStore } from '@/store/example.ts'
let exampleStore = useExampleStore()
function add (){
//第一种写法
exampleStore.$patch({
sum : exampleStore.sum++
})
//第二种写法
exampleStore.$patch((state)=>{
state.sum++
})
}
第三种写法 用到了第一步存值(初始化)中的action
中定义的方法
//example.vue
<h1>{{sum}}</h1>
<button @click="add">+1</button>
import { useExampleStore } from '@/store/example.ts'
let exampleStore = useExampleStore()
function add (){
exampleStore.increment()
}
监视pinia中的数据的变化($subscribe
)
$subscribe
收到两个参数
第一个参数:本次修改的信息(没什么用
)
第二个参数:真正的
数据
//example.vue
import { useExampleStore } from '@/store/example.ts'
let exampleStore = useExampleStore()
exampleStore.$subscribe((mutate,state)=>{
console.log('产生了变化')
})