本文主要介绍了Vue.js在数组中插入重复数据的实现代码,需要的朋友可以参考下,希望能帮助到大家。
1、在默认的情况下,Vue.js默认不支持往数组中加入重复的数据。可以使用track-by="$index"来实现。
2、不使用track-by="$index"的数组插入,数组不支持重复数据的插入
2.1 JavaScript代码
window.onload = function() {
vm = new Vue({
el: '#app',
data: {
arrMsg: ['apple', 'orage', 'pear']
},
methods: {
add: function() {
this.arrMsg.push('tamota');
}
}
});
}
2.2 html代码
{{value}}
增加数据
2.2 结果
3、使用track-by="$index"的数组插入,数组支持重复数据的插入
3.1 Javascript代码
window.onload = function() {
vm = new Vue({
el: '#app',
data: {
arrMsg: ['apple', 'orage', 'pear']
},
methods: {
add: function() {
this.arrMsg.push('tamota');
}
}
});
}
3.2 html代码
{{value}}
增加数据
3.3 结果
4、完整代码
.container{
margin-top: 20px;
}
window.onload = function() {
vm = new Vue({
el: '#app',
data: {
arrMsg: ['apple', 'orage', 'pear']
},
methods: {
add: function() {
this.arrMsg.push('tamota');
}
}
});
}
{{value}}
增加数据
ps:下面看下vue 数组重复,循环报错
Vue.js默认不支持往数组中加入重复的数据。可以使用track-by="$index"来实现。
相关推荐: