简体   繁体   English

如何使具有扩展(...)表示法的对象具有反应性?

[英]How to make an Object with spread (…) notation reactive?

I'm trying to change the opacity attribute of an object and make that change reactive: 我正在尝试更改对象的不透明度属性并使该更改具有反应性:

Component.vue: Component.vue:

<child-component :common="itemCommon"></child-component>

<script>
data () {
  return {
    rest: {}
  }
},

computed: {
  itemCommon () {
    return {
      item: {
        opacity: 1,
        ...this.rest
      }
    }
  }
},

beforeMount () {
  this.rest = { name: 'a' }
}
<script>

childComponent.vue: childComponent.vue:

<script>
props: {
  common: {
    type: Object,
    default () {
      return {}
    }
  }
},

beforeMount () {
  this.common.item.opacity = 0
}
</script>

The opacity attribute won't be set to 0 . opacity属性将不会设置为0 Vue doesn't consider itemCommon Vue不考虑itemCommon

How to modify the code so itemCommon becomes reactive? 如何修改代码,使itemCommon成为反应式的?

Generally, vue watches the changes on components' data properties, and change the view when it sees a data change. 通常,vue监视组件data属性的更改,并在看到data更改时更改视图。 So to make some data reactive , we have to declare it in a component's data . 因此,为了使某些数据具有响应性 ,我们必须在组件的data声明它。 You don't have opacity in either component here, so it's probably not picked up by vue. 您在这两个组件中都没有opacity ,因此可能不会被vue拾取。 Adding it to the parent's data should fix it, but you'll get a warning like directly setting prop in child , then you should move this.common.item.opacity = 0 to the parent. 将其添加到父级的data可以解决该问题,但是会收到警告,例如directly setting prop in child ,然后应将this.common.item.opacity = 0移到父级。 You can find plenty searching the warning but here briefly: prop will commonly be changed in the parent, changing it also in the child is confusing, and by design, the child provides functionality/interface, the parent, who makes use of the child, give data to the child in runtime, trusting the child handling the data with the functionality we expect, so we achieve loose coupling . 您可以找到很多搜索警告的信息,但这里只是简要介绍一下:通常会在父级中更改prop ,在子级中也更改它,这会造成混淆,并且通过设计,子级提供了功能/界面,父级使用了子级,在运行时将数据提供给子级,并以期望的功能信任处理数据的子级,因此实现了松耦合 (this is also usually called a one-way data flow) (通常也称为单向数据流)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM