Vue3中使用Pinia修改State的五种方式
作者:xyphf_和派孔明
这篇文章主要介绍了Vue3中使用Pinia修改State的五种方式,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧
修改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>到此这篇关于Vue3中使用Pinia修改State的方法的文章就介绍到这了,更多相关vue3使用Pinia修改state内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
