Vue js动态添加属性而不是被动 [英] Vue js dynamically added property not reactive
问题描述
我有一个组件显示有一个名为 obj
的道具。 obj
有两个属性: obj.title
和 obj.body
。每个都绑定到文本字段,以便被动和可编辑。
I have a component which displays has a prop called obj
. obj
has two properties: obj.title
and obj.body
. Each is bound to a textfield so as to be reactive and editable.
<div id="app">
<controller :obj="{title: 'TITLE'}"></controller>
</div>
<template id="controller">
<input type="text" v-model="obj.title">
<p>{{ obj.title }}</p>
<input type="text" v-model="obj.body">
<p>{{ obj.body }}</p>
</template>
title
属性是道具的一部分它绑定到组件。但是在创建的回调期间动态添加了 body
属性。这是js:
The title
property is part of the prop which is bound to the component. But the body
property has been added dynamically during the created callback. Here is the js:
Vue.component('controller', {
template: '#controller',
props: ['obj'],
created: function() {
this.obj.body = "BODY";
},
});
new Vue({
el: '#app',
});
问题是正文
属性不是表现得很反应。 {{obj.body}}
不会反映对正文
文本字段的更改。
The problem is that the body
property isn't behaving reactively. Changes to the body
textfield are not reflected by {{ obj.body }}
.
vue网站有一节关于添加和删除属性,但我无法得到他们的建议。
The vue website has a section about Adding and Deleting Properties, but I couldn't get their suggestions to work.
这是一个 jsfiddle ,展示了这个问题。
Here is a jsfiddle demonstrating the problem.
注意:有人建议我在<$ c的同时声明 body
属性$ c> title property。这可行,但对于我的用例,需要动态添加属性。
Note: it has been suggested that I declare the body
property at the same time as the title
property. This would work, but for my use-case the property needs to be added dynamically.
推荐答案
我选择这个作为Accepted解决方案,因为我会推荐给其他有相同问题的人。
I have selected this as the Accepted solution because it is what I would recommend to someone else with the same problem.
用户螃蟹注意到,只有在道具参考更新时才能重新建立反应性。
As user crabbly noticed, the reactivity can only be re-established if the prop's reference is updated.
我认为最好的方法是做一个浅拷贝:
I think the nicest way to do this is by making a shallow copy:
created: function() {
this.obj.body = 'BODY'
/**
* ... other code that adds other properties and messes around with obj...
*/
this.obj = Object.assign({}, this.obj);
}
...此处, Object.assign
负责更新参考。
... here, Object.assign
is responsible for updating the reference.
IE目前不支持此解决方案,但任何克隆功能都可以(例如 this.obj = jQuery.extend({} ,this.obj);
也有效。)
This solution is currently not supported by IE, though any "clone" function will do (e.g. this.obj = jQuery.extend({}, this.obj);
also works).
这篇关于Vue js动态添加属性而不是被动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!