[Vuejs]-Vue 3 – differences between reactive value return – toRef and computed

0πŸ‘

In my opinion when you return a variable from a composable, that means you want to work with that variable as an output of composable in your components. So when you return it as readonly, that means you don’t want to change it during other operations in the component and if you change that Vue create warning for you. But when you return it as computed that means you want to have the value of your main variable (here called userState), but also if needed you change it in your component. Here I posted the codes of my component and composable to determine the above sentences clearly:

component code:

<template>
  <div>
    <p>{{ emailComputed }}</p>
    <p> {{ email }} </p>
    <button @click="changeEmail">change email</button>
  </div>
</template>

<script>
/* importing composable */
import {useReadOnly} from "../composables/codeReadOnly";
import {reactive} from "vue";
export default {
  setup() {
   
    const { email, emailComputed } = useReadOnly();

    const changeEmail = function () {
      /* uncomment the line below and comment second line */
      // ----------------------------------------------------
      // emailComputed.value = "new-email@email.com";
      email.value = "new-email@email.com";
    }

    return {
      emailComputed,
      email,
      changeEmail
    }

  }
}
</script>

<style scoped>

</style>

composable code:

import {reactive, computed, toRef, readonly} from "vue";
export function useReadOnly() {
    const userState = reactive({
        email: 'test@test.com',
        name: "",
    })

    return {
        email: readonly(toRef(userState, 'email')),
        emailComputed: computed({
            get: () => userState.email,
            set: (val) => {
                userState.email = val;
            }
        })
}
}

In the above code you can change the value of emailComputed by clicking the button, but you can not change the value of email in your main component. That is the difference I could understand, but maybe there are other differences also that I don’t know.

Leave a comment