Search code examples
vue.jsvuejs3refvue-composition-api

what is the correct way of assigning vue state (ref()) to each other?


I am a little confused about using ref() in vue 3 (script setup) because of the ref().value. what I want to know is should I use ref().value = ref().value or ref()=ref() I provide an example:

<script setup>
let stateOne=ref('1')
let stateTwo=ref('2')

//This way:
stateOne.value=stateTwo.value

//Or this:
stateTwo=stateOne

</script>

thank you for helping me understand this concept better


Solution

  • Assign value (correct way)

    stateOne.value = stateTwo.value;
    

    This will make the values equal, so if you change stateOne.value, stateTwo.value will remain the same.

    Reassign the variable

    stateTwo = stateOne;
    

    Will only work if stateTwo is defined with let and will make the variables the same, so if stateOne.value is set to "something" stateTwo.value will also be updated