Vue: 如何向 vue(对象)数据添加新属性?

创建于 2016-07-28  ·  3评论  ·  资料来源: vuejs/vue

我的数据在下面

 data: {
                contacts: {
                    "1": {
                        isSelected: false,
                        UID:"1",
                        cardType: 0      
                    },
                    "2": {
                        isSelected: false,
                        UID:"2",
                        cardType: 0    
                    },
                    "3": {
                        isSelected: false,
                        UID:"3",
                        cardType: 0    
                     },
            }
...

我可以使用这种方法来添加新的联系人,但是它有一个兼容性问题,所以我想知道有没有其他方法可以向对象添加新属性,或者我最好改为使用数组而不是对象。
this.contacts = Object.assign({}, this.contacts, newObj);

非常感谢。

最有用的评论

谢谢,使用set方法,现在可以了。

this.$set('contacts[' + newPsgId + ']', newObj)
Vue.set(this.contacts[newPsgId], 'name', this.editPsgName);  

所有3条评论

阅读文档: Vue.set

谢谢,使用set方法,现在可以了。

this.$set('contacts[' + newPsgId + ']', newObj)
Vue.set(this.contacts[newPsgId], 'name', this.editPsgName);  

以前的解决方案对我不起作用(Vue ^ 3.0.0)
自己做。 希望这可以帮助某人。

this.$set(this.contacts, newPsgId, newObj)
此页面是否有帮助?
0 / 5 - 0 等级