修改Pinia仓库的值有5种方式
src/store/index.ts
import { defineStore } from 'pinia';
import { Names } from './store-name';
export const useTestStore = defineStore(Names.Test, {
state:()=>{
return {
current:1111,
name: '小满111'
}
},
getters:{ // 类似computed计算属性 同样有缓存的
},
actions:{ // 类似 methods方法 可以做同步、异步操作 提交state
}
});
第一种修改State的方式
<template>
<div>
pinia: {
{ Test.current }} --- {
{ Test.name }}
<button @click="change">change</button>
</div>
</template>
<script setup lang="ts">
import {useTestStore} from './store';
const Test = useTestStore();
// 第一种修改State的方式
const change = () => {
Test.current++
}
</script>
<style scoped>
</style>
第二种修改State的方式
<template>
<div>
pinia: {
{ Test.current }} --- {
{ Test.name }}
<button @click="change">change</button>
</div>
</template>
<script setup lang="ts">
import {useTestStore} from './store';
const Test = useTestStore();
// 第二种修改State的方式 批量修改对象属性
const change = () => {
Test.$patch({
current: 999,
name: '李四'
})
}
</script>
<style scoped>
</style>
第三种修改State的方式
<template>
<div>
pinia: {
{ Test.current }} --- {
{ Test.name }}
<button @click="change">change</button>
</div>
</template>
<script setup lang="ts">
import {useTestStore} from './store';
const Test = useTestStore();
// 第三种修改State的方式 向$patch中传入工厂函数 可以写逻辑
const change = () => {
Test.$patch((state) => {
if(state.current>1113){
state.current--;
state.name = '罗翔老师';
} else {
state.current++;
state.name = '罗永浩老师';
}
})
}
</script>
<style scoped>
</style>
第四种修改State的方式
<template>
<div>
pinia: {
{ Test.current }} --- {
{ Test.name }}
<button @click="change">change</button>
</div>
</template>
<script setup lang="ts">
import {useTestStore} from './store';
const Test = useTestStore();
// 第四种修改State的方式 覆盖这个state对象
const change = () => {
Test.$state = {
current: 1024,
name: '罗城将军'
}
}
</script>
<style scoped>
</style>
第五种修改State的方式
调用actions里面的方式
在 src/store/index.ts 里面的actions里面写个方法
import { defineStore } from 'pinia';
import { Names } from './store-name';
export const useTestStore = defineStore(Names.Test, {
state:()=>{
return {
current:1111,
name: '小满111'
}
},
getters:{ // 类似computed计算属性 同样有缓存的
},
actions:{ // 类似 methods方法 可以做同步、异步操作 提交state
setCurrent(num:number){ // 注意此处不要写箭头函数,否则this指向就不对了
this.current = num;
}
}
});
再在组件里面调用
<template>
<div>
pinia: {
{ Test.current }} --- {
{ Test.name }}
<button @click="change">change</button>
</div>
</template>
<script setup lang="ts">
import {useTestStore} from './store';
const Test = useTestStore();
// 第五种
const change = () => {
Test.setCurrent(5173); // 直接调用setCurrent函数
}
</script>
<style scoped>
</style>