文章目录
一、基本使用
//index.ts
import {defineStore} from 'pinia'
//1.定义并导出容器
//参数1:容器的ID必须唯一,将来pinia会把所有的容器挂载到根容器
//参数2:选项对象
//返回值:一个函数,调用得到容器实例
export const useMainStore = defineStore('main',{
//类似于组件的data,用来存储全局状态
//1.必须是函数:为了在服务端渲染时避免交叉请求导致的数据状态污染
//2.必须是箭头函数,为了更好的ts类型推导
state:()=>{
return{
count:100,
foo:'bar',
arr:[1,2,3]
}
},
//类似于组件的computed,用来封装计算属性,有缓存的功能
getters:{
//函数接收一个可选参数state状态对象
count10(state){
console.log('count10调用了');
return state.count + 10
}
},
//类似于组件的methods,封装业务逻辑,修改state
actions:{
// 注意:不能使用箭头函数定义action,因为箭头函数绑定外部this
changeState(num: number){
this.count += num
this.foo = 'hhh'
this.arr.push(5)
}
}
})
//HelloWorld.vue
<template>
<p>{{ count }}</p>
<p>{{ foo }}</p>
<p>{{mainStore.arr}}</p>
<p>{{mainStore.count10}}</p>
<p>{{mainStore.count10}}</p>
<hr />
<p>
<button @click="handleChangeState">修改数据</button>
</p>
</template>
<script lang="ts" setup>
import { storeToRefs } from "pinia";
import { useMainStore } from "../store/index";
const mainStore = useMainStore();
console.log(mainStore.count);
//这样拿到的数据不是响应式的
// const {count,foo} = mainStore
//解决方法:把解构出来的数据做ref响应式代理
const { count, foo } = storeToRefs(mainStore);
console.log(count.value);
//修改数据
const handleChangeState = () => {
//方式一:
// mainStore.count++;
// mainStore.foo = 'hello'
//方式二:修改多个数据建议使用$patch批量更新
// mainStore.$patch({
// count:mainStore.count + 1,
// foo:'hello',
// arr:[...mainStore.arr,4]
// })
//方式三:更好的批量更新方式:$patch一个函数
// mainStore.$patch(state=>{
// state.count++
// state.foo = 'hello'
// state.arr.push(4)
// })
//方式四:逻辑较多的时候可以封装到actions做处理
mainStore.changeState(10)
};
</script>
<style>
</style>