一、 安装
yarn add pinia
# 或者使用 npm
npm install pinia
二、 main.ts 中引入注册
import { createApp } from 'vue'
import App from './App.vue'
import {createPinia} from "pinia" // 1. 引入
const app = createApp(App)
const pinia = createPinia() // 2. 创建
app.use(pinia) // 3. 注册
app.mount('#app')
三、 src下创建store文件夹,文件夹中存放ts文件每个小仓库
这里我创建一个count.ts
import {defineStore} from "pinia"
import {ref,computed} from "vue";
// 组合式写法
export const useCountStore = defineStore("count",()=>{
// 数据,相当于state
const num = ref(5)
const name = ref("狗子")
// 计算属性,相当于getters
const getName = computed(():string=>{
return name.value += "!"
})
const getNum = computed(():number=>{
return num.value * 10
})
// 方法,相当于actions
function increment(newValue: number):void{
num.value+=newValue
}
// 最后必须return,否侧外界拿不到
return {
num,
name,
increment,
getNum,
getName
}
})
count.ts 还有一种选项式写法
import {defineStore} from "pinia"
// 选项式写法
export const useCountStore = defineStore("count",{
state() {
return{
num:5,
name:"狗子"
}
},
actions:{
increment(newValue: number):void{
this.num+=newValue
},
},
getters:{
getNum(state){
return state.num * 10
},
getName(state){
return state.name += "!"
}
}
})
四、组件中读取与修改数据
1. 读取数据,可直接读取
<script setup lang="ts">
import {useCountStore} from "@/store/count"
const countStore = useCountStore()
console.log(countStore.num) // 5
</script>
2. 修改数据的三种方式
// 第一种:改一个
countStore.num += 1
// 第二种:$patch 改多个
countStore.$patch({
num: ++countStore.num,
name: countStore.name+="~",
})
// 第三种:还记得count.ts中定义的方法吗,这就用上了
countStore.increment(5);
五、storeToRefs:用于解构出的数据依然保持响应式
<script setup lang="ts">
import {useCountStore} from "@/store/count"
import {storeToRefs} from "pinia"
const countStore = useCountStore()
// 是响应式数据
const {num, name,getNum,getName} = storeToRefs(countStore)
// 不是响应式数据
const {num, name,getNum,getName} = countStore
</script>
<template>
<div class="count">
解构有啥用?答:读取数据更方便
不解构:{{ countStore.num }}
解构:{{ num }}
</div>
</template>
六、监听仓库中的数据发生改变:$subscribe
mutate:包含修改的方式与发生变化的值等等
state:包含仓库中的数据
countStore.$subscribe((mutate,state) => {
console.log(mutate,state)
})