1

假设您有一个reactive想要导出的对象,如此readonly所述。

import { reactive, readonly } from '@vue/composition-api'

const graph = reactive({
  profile: {
    givenName: '',
    surName: '',
  }
})

return {
   profile: () => readonly(graph.profile)
}

该方法readonly()似乎不是 VueCompositionAPI 的一部分:

“在 '@vue/composition-api' 中找不到导出 'readonly'

我知道使用时ref您可以简单地使用computed属性

return {
   profile: computed(() => graph.profile)
}

但是对于一个reactive我们不想.value每次都使用的对象,这似乎是不可能的。我在这里错过了一些非常明显的东西吗?

4

1 回答 1

2

是的,reactive由于语言(JS)的限制,不属于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 }
于 2020-05-26T16:43:32.017 回答