Skip to content

响应性丟失 简单 #Composition API #Reactivity:Utilities

By webfansplz @webfansplz

接受挑战    接受挑战(通过单元测试)    English

JavaScript 中,我们经常解构/扩展对象。

Vue.js中,我们同样解构/扩展“响应式”对象,但它会失去响应性。

如何保证解构/扩展不丢失响应性 ? 让我们开始吧 !

<script setup lang="ts">
import { reactive } from "vue"

function useCount() {
  const state = reactive({
    count: 0,
  })

  function update(value: number) {
    state.count = value
  }

  return {
    state,
    update,
  }
}

// 确保解构不丢失响应性
const { state: { count }, update } = useCount()

</script>

<template>
  <div>
    <p>
      <span @click="update(count-1)">-</span>
      {{ count }}
      <span @click="update(count+1)">+</span>
    </p>
  </div>
</template>

分享你的解答 查看解答