解构赋值响应式
原创...小于 1 分钟
如果直接从 pinia 中解构数据,会丢失响应式
<template>
<p>count:{{ count }}</p>
<p>doubleCount:{{ doubleCount }}</p>
<button @click="countAdd">count ++</button>
</template>
<script setup lang="ts">
import { useCounterStore } from "@/stores/counter";
const counterStore = useCounterStore();
const { count, doubleCount } = counterStore;
const countAdd = () => {
counterStore.increment();
};
</script>
上述代码,我们操作加减的时候会发现,内容根本不会发生变化,这就是我们使用解构赋值之后,失去了响应式,我们可以用 storeToRefs
来解决找个问题
<template>
<p>count:{{ count }}</p>
<p>doubleCount:{{ doubleCount }}</p>
<button @click="countAdd">count ++</button>
</template>
<script setup lang="ts">
import { useCounterStore } from "@/stores/counter";
import { storeToRefs } from "pinia";
const counterStore = useCounterStore();
const { count, doubleCount } = storeToRefs(counterStore);
const countAdd = () => {
counterStore.increment();
};
</script>
Powered by Waline v2.15.7