解构赋值响应式
原创2026/3/5小于 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>至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。