Home > OS >  Vue3 reactive counter to setup
Vue3 reactive counter to setup

Time:07-27

I'm trying to make the counter data be transmitted after clicking in the setup, but it doesn't work, what's wrong? Thanks.

setup(props) {
    let count = ref(1)
    let obj = reactive({ count })
    let form = reactive({
        name: props.user.name,
        count: obj.count,
 })
return { form, count, obj }

I change count by:

@click="count  "

And after click data in setup(props) dont update, BUT if i write like as is, it has been reactive:

setup(props) {
    let count = ref(1)
    let obj = reactive({ count })
    let form = reactive({
        name: props.user.name,
        count: obj,
 })
return { form, count, obj }

And after click count: obj will be update, but as it should be the data is passed as an object:

{"count":3}

Why if I try to use obj.count doesn't work dynamically?

CodePudding user response:

TL;DR;

it's because when you access the ref from inside the reactive to assign it to a value it gets the value only, and the reactivity is lost.

here is an example

<script>
  import { ref, reactive } from 'vue';

  export default{
    setup(props) {
      let count = ref(1)
      let obj = reactive({ count })
      let form = reactive({
        count: obj.count,
        obj: obj
      })
      return { form, count, obj }
    }
  }
</script>

<template>
  <h1 @click="count  ">{{ count }}</h1>
  <h1 @click="obj.count  ">{{ obj }}</h1>
  <h1 @click="form.count  ">{{ form }}</h1>
</template>

If you click on @click="count ", the count, obj.count and form.obj.count are updated, but the form.count isn't.

It may not be immediately clear, but when you assign obj.count to form.count, it is not the ref that is passed. Instead the value is resolved, and that is assigned to the value and the reactivity is lost. You can look into the advanced reactivity for some other options. For example, if you use shallowReactive like: let obj = shallowReactive({ count: count }), then the count will remain reactive, but you will need to update the shallowRef with obj.count.value instead of obj.count

example 2

<script>
  import { ref, reactive, shallowRef, shallowReactive } from 'vue';

  export default{
    setup(props) {
      let count = ref(1);
      let obj = shallowReactive({ count: count });
      let form = reactive({
        count: obj.count,
        obj: obj
      });
      return { form, count, obj };
    }
  }
</script>

<template>
  <h1 @click="count  ">{{ count }}</h1>
  <h1 @click="obj.count.value  ">{{ obj }}</h1>
  <h1 @click="form.count  ">{{ form }}</h1>
</template>
  • Related