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.
- [Vuejs]-Data not added to firebase realtime database
- [Vuejs]-How to display image using address in DB using Vue.js?