跳至主要內容

解构赋值响应式

刘春龙原创...小于 1 分钟WEB前端Vue3Pinia状态管理教程文档

如果直接从 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