【问题标题】:Vue.js3 - Reaonly on nested objectVue.js 3 - 只读嵌套对象
【发布时间】:2021-04-27 02:15:33
【问题描述】:

有没有办法使用新的 Vue.js Reactivity API 将对象键绑定到现有的 Ref 值作为只读?

示例

setup() {
  const input = ref({
    firstName: 'Bob',
    email: 'bob@so.com'
  })

  const args = {
    postID: 32,
    email: readonly(input.value.email)
  }

  return { input, args }
}

这不起作用。
args.email 没有得到更新。

【问题讨论】:

    标签: javascript vue.js vue-reactivity


    【解决方案1】:

    正如@boussadjra-brahim 指出的那样,readonly 不能用于嵌套字段。
    只有在不复制整个对象的情况下才能使用 computed 的解决方法。

    const args = computed(() => {
      return {
        post_id: 32,
        email: input.value.email,
      }
    })
    

    【讨论】:

      【解决方案2】:

      Readonly 接受使用 refreactive 创建的属性,而不是该属性中的嵌套字段,以便反应:

       const input = ref({
          firstName: 'Bob',
          email: 'bob@so.com'
        })
      
        const args =readonly(input)
      

      【讨论】:

      • 在这种情况下,我不一定想对整个对象使用只读。使用计算可能是一个更好的解决方案,然后我猜。
      • 我刚刚提到,在这种情况下 readonly 看起来没用,建议像您一样使用 computed,因为它是响应式和不可变的