a small vue issue about set value to object.value

116 views Asked by At
<template>
    <button @click="random(randomNum)">Click to plus {{count}}</button>
</template>

<script setup>
import { ref } from "vue"
const count = ref ()
const randomNum = ref (Math.floor(Math.random()*1000))
function random(randomNum) {
  count.value=randomNum;
}
</script>

When I use count.value = randomNum.value, the result is not showing. I think randomNum is an object. If I set value to count.value, it should use randomNum.value, but it's not rendering.

2

There are 2 answers

0
tony19 On BEST ANSWER

The problem is the randomNum ref is only initialized to a random number once:

<script setup>
                    /* set only once */
const randomNum = ref(Math.floor(Math.random()*1000))
⋮
</script>                        

That randomNum ref is passed to random() in the click-handler, but that ref's value never changes, so the clicks will appear to do nothing:

<template>                  
  <button @click="random(randomNum)">Click</button>
</template>

Solution

Instead of passing the randomNum ref, generate a new random number inside random() on every call:

<script setup>
function random() {
                       /* new random number */
  count.value = Math.floor(Math.random() * 1000)
}
⋮
</script>

<template>
  <button @click="random()">Click</button>
</template>

demo

2
Jazuly On

try this..

<template>
   <button @click="random()">Click to plus {{count}}</button>
</template>

<script>
import { defineComponent, ref } from "vue";

export default defineComponent({
  setup() {
    const count = ref(0)
    const randomNum = ref(Math.floor(Math.random()*1000))

    const random = () => {
      count.value = randomNum.value;
    }

    return {
      count,
      random,
    };
  },
});
</script>