添加新的键,以使空数据对象在VUEJS中不起作用
我有与VUE数据有关的问题。
我用一个空对象创建了数据。
data(){
return {
myObj: {}
}
}
并这样的功能:
methods: {
changeMyObj() {
this.myObj.newKey = 'aaaa';
}
}
然后,我单击此单击,在模板上显示它
<a @click="changeMyObj">Click change</a>
{{myObj.newKey}}
,嵌套键不会在模板上呈现。如何解决这个问题?
注意:我不遇到Vuex或React状态的问题。
I have question related to data of Vue.
I created data with an empty object.
data(){
return {
myObj: {}
}
}
and function like this:
methods: {
changeMyObj() {
this.myObj.newKey = 'aaaa';
}
}
Then I show it on template by click
<a @click="changeMyObj">Click change</a>
{{myObj.newKey}}
With this click, the nested key is not rendered on template. How can I resolve this issue?
Note: I do not meet this issue with Vuex or state of React.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为 vue.js反应性。实际上,在这里,您正在修改一个值时未声明的值,并且VUE无法跟踪更改。
您可以使用
vue.set
方法更新值,该方法允许VUE跟踪数据。您还可以对对象进行深层复制,而不仅仅是添加密钥。
可以使用 spread operator 。
例如,
这里是使用两个版本的一个小示例
This happens because of vue.js reactivity. In fact, here you are modifying a value that was not declared when the component mounted and Vue cannot track the changes.
You can update values by using the
Vue.set
method which allows Vue to track the data.You can also make a deep copy of the object instead of just adding the key.
This can be done using the spread operator.
For example
Here is a small example using the two versions
我找到了解决方案。
我认为这不是解决方案,尽管它没有区别:
如果有人可以解释为什么请告诉我。谢谢
I found the solution for this.
I do not think it is solution while it has no difference with:
If someone can explain why please let me know. Thanks
在现有对象中分配新属性的正确方法是
vue.set(this.myobj,'newkey','aaaa')
使其具有反应性,而不是this.myobj.newkey = 'aaaa'
demo :
Correct way to assign a new property in an existing object is
Vue.set(this.myObj, 'newKey', 'aaaa')
to make it reactive instead ofthis.myObj.newKey = 'aaaa'
Demo :