假设您有一个reactive
对象,要按照here的说明导出为readonly
。
import { reactive, readonly } from '@vue/composition-api'
const graph = reactive({
profile: {
givenName: '',
surName: '',
}
})
return {
profile: () => readonly(graph.profile)
}
方法readonly()
似乎不是VueCompositionAPI的一部分:
“在'@ vue / composition-api'中找不到导出'只读'
我知道,使用ref
时,您可以简单地使用computed
属性
return {
profile: computed(() => graph.profile)
}
但是对于reactive
对象,我们不想每次都使用.value
,这似乎是不可能的。我在这里错过了什么超级明显的东西吗?
答案 0 :(得分:2)
是的,由于语言(JS)的限制,reactive
不属于composition api插件。 Vue 3.0将通过代理解决该问题。
第二个问题,我将直接给您答案:否,您不能在不使用计算属性的情况下将反应式值作为只读属性返回。如果不使用代理实现(Vue 3.0+),则不可能。
如果您问我,我将根据您的computed
状态定义reactive
个变量的块。
const graph = reactive({
profile: {
givenName: '',
surName: '',
}
})
return {
profile: computed(() => graph.profile),
another: computed(() => graph.another)
}
您将不得不使用.value
,但是至少您的返回会更清晰,并且您可以在不破坏反应性的情况下进行对象分解。如果我们对最后一种方法充满创意,您甚至可以创建自己的助手:
function readonlyState(state) {
const computeds = {}
for (let key in state) {
computeds[key] = computed(() => state[key])
}
return computeds
}
并使用它:
const graph = reactive({
profile: {
givenName: '',
surName: '',
}
})
return readonlyState(state) // { profile }