优点:
1.支持vue2、vue3
2.抛弃Mutations的操作,只有state、getters和actions
3.不需要嵌套模块,符合Vue3的Composition api
4.完整的TypeScript支持
5.代码更加简洁
定义状态容器:store
import { defineStore } from "pinia";
export const mainStore = defineStore('main',{
state:()=>{
return {
helloWord:'hello word!',
count:0
}
},
getters:{},
actions:{}
})
使用state数据
注意:当结构store时要使用storeToRefs才能实现响应式
<template>
<div>{{store.helloWord}}</div>
<div>{{store.count}}</div>
<!-- -->
<div>{{helloWord}}</div>
<div>{{count}}</div>
</template>
<script setup lang="ts">
import {mainStore} from "../store/index"
import { storeToRefs } from "pinia";
const store = mainStore()
// const {helloWord,count} = store
const {helloWord,count} = storeToRefs(store)
</script>
<style scoped>
</style>
修改数据状态
<template>
<div>
<button @click="handleClick">修改数据状态1</button>
<button @click="handleClickPatch">修改数据状态2</button>
<button @click="handleClickMethod">修改数据状态3</button>
<button @click="handleClickActions">修改数据状态4</button>
</div>
</template>
<script setup lang="ts">
import { mainStore } from '../store';
const store = mainStore()
// 第一种方法
const handleClick=()=>{
store.count++
}
// 第二种方法
const handleClickPatch=()=>{
store.$patch({
count:store.count+2,
helloWord:store.helloWord=="你好世界"?'hello word!':"你好世界"
})
}
// 第三种方法$patch传递函数
const handleClickMethod=()=>{
store.$patch((state)=>{
state.count++
state.helloWord=state.helloWord=="你好世界"?'hello word!':"你好世界"
})
}
//第四种方式 actions
const handleClickActions=()=>{
store.changeState()
}
</script>
<style scoped>
</style>
store
//定义状态容器
//修改容器中的state
//仓库中的action使用
import { defineStore } from "pinia";
export const mainStore = defineStore('main',{
state:()=>{
return {
helloWord:'hello word!',
count:0
}
},
getters:{},
actions:{
changeState(){
this.count++
}
}
})
getters使用
需求:隐藏电话号码
<template>
<div>{{store.helloWord}}</div>
<div>{{store.count}}</div>
<!-- 调用的是getters里的方法 -->
<div>{{store.phoneHidden}}</div>
<!-- -->
<div>{{helloWord}}</div>
<div>{{count}}</div>
<div>{{phoneHidden}}</div>
</template>
<script setup lang="ts">
import {mainStore} from "../store/index"
import { storeToRefs } from "pinia";
const store = mainStore()
// const {helloWord,count} = store
const {helloWord,count,phoneHidden} = storeToRefs(store)
</script>
<style scoped>
</style>
store
import { defineStore } from "pinia";
export const mainStore = defineStore('main',{
state:()=>{
return {
helloWord:'hello word!',
count:0,
phone:18356226359
}
},
getters:{
phoneHidden(state){
console.log("getters被调用了");
return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/,'$1****$2')
}
// phoneHidden():String{
// console.log("getters被调用了");
// return this.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/,'$1****$2')
// }
},
actions:{
changeState(){
this.count++
}
}
})