Skip to content

3 - losing-reactivity #2156

Open
Open
@smallma

Description

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

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

function update(value: number) {
  state.count = value;
}
</script>

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

Activity

smallma

smallma commented on Oct 11, 2023

@smallma
Author
<script setup lang="ts">
import { reactive, toRefs } from "vue"

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

  function update(value: any, addNum) {
    console.log('value.count: ', value.count.value);
    state.count = value.count.value + addNum;
  }

  return {
    state: toRefs(state),
    update,
  }
}

// Ensure the destructured properties don't lose their reactivity
const { state, update } = useCount()
</script>

<template>
  <div>
    <p>
      <span @click="update(state, -1)">-</span>
      {{ state.count }}
      <span @click="update(state, 1)">+</span>
    </p>
  </div>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @smallma

        Issue actions

          3 - losing-reactivity · Issue #2156 · webfansplz/vuejs-challenges