var vue_app = new Vue({
el: '#id1',
data: {
v1:[],
},
methods:{
pushUnique: function() {
this.v1.push({'id':1,'name':'josh'});
this.v1.push({'id':1,'name':'josh'}); //this should not work.
},
},
});
在上面的代码中,不应执行第二次推送。我想保持id
唯一。在Vue中如何做到这一点。
谢谢
答案 0 :(得分:0)
我将转向将数据存储在对象中(由id
键控),并使用计算属性生成v1
数组。例如
data: {
v1obj: {}
},
computed: {
v1 () {
return Object.keys(this.v1obj).map(id => ({ id, name: this.v1obj[id] }))
}
}
然后,您可以使用Object.prototype.hasOwnProperty()
之类的方法来检查现有密钥...
methods: {
pushUnique () {
let id = 1
let name = 'josh'
if (!this.v1obj.hasOwnProperty(id)) {
this.v1obj[id] = name
}
}
}