Suppose you have a reactive object that you want to export as readonly as explained here.
import { reactive, readonly } from '@vue/composition-api'
const graph = reactive({
profile: {
givenName: '',
surName: '',
}
})
return {
profile: () => readonly(graph.profile)
}
The method readonly() does not seem to be a part of the VueCompositionAPI:
"export 'readonly' was not found in '@vue/composition-api'
I know that when using ref you can simply use a computed property
return {
profile: computed(() => graph.profile)
}
But for a reactive object, where we don't want to use the .value every time, this doesn't seem possible. Am I missing something super obvious here?
Yes, reactive doesn't belong to composition api plugin because of the limitation of the language (JS). Vue 3.0 will solve that via proxies.
The second question, I'll give you a direct answer: no, you can't return a reactive value as a read-only property without using a computed property. That's not possible if you don't use the proxies implementation (Vue 3.0+).
If you ask me, I'd go with defining chunks of computed vars based on your reactive state.
const graph = reactive({
profile: {
givenName: '',
surName: '',
}
})
return {
profile: computed(() => graph.profile),
another: computed(() => graph.another)
}
You'd have to use .value but at least your return will be clearer and you'll allow object destructuring without tearing down reactivity. If we get creative with the last approach, you can even create your own helper:
function readonlyState(state) {
const computeds = {}
for (let key in state) {
computeds[key] = computed(() => state[key])
}
return computeds
}
And use it:
const graph = reactive({
profile: {
givenName: '',
surName: '',
}
})
return readonlyState(state) // { profile }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With