我试图更改对象的不透明度属性并使该更改变为反应性:
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:
<script>
props: {
common: {
type: Object,
default () {
return {}
}
}
},
beforeMount () {
this.common.item.opacity = 0
}
</script>
opacity
属性不会设置为0
。 Vue不考虑itemCommon
如何修改代码以使itemCommon
变为被动?
答案 0 :(得分:1)
通常,vue会监视组件“data
”属性的更改,并在看到data
更改时更改视图。因此,为了使一些数据被动,我们必须在组件的data
中声明它。您在这两个组件中都没有opacity
,因此它可能不会被vue选中。将其添加到父级data
应该会修复它,但是您会收到directly setting prop in child
之类的警告,然后您应该将this.common.item.opacity = 0
移到父级。您可以找到大量搜索警告但在此简要说明:prop
通常会在父级中更改,更改它也会在子级中造成混乱,并且通过设计,子级提供功能/接口,父级,谁使用对于孩子,在运行时向孩子提供数据,信任处理数据的孩子具有我们期望的功能,因此我们实现松散耦合。 (这通常也称为单向数据流)