[英]Vue.js adding an element to an array from another array
我想从我在我的方法对象的单独方法中创建的另一个数组中,向Vue实例内的数据函数中的数组添加元素,这是我的代码
export default { data(){ return { names: ['Obama','kenedy','lincolen','bush'] } }, methods: { addItem(){ let funnyPeople = ['Donald Duck','Tom','Jerry','Donald Trump'] funnyPeople.forEach(name => { this.names.push(name); }) } } }
<template> <div> <ul> <li v-for="name in names">{{ name }}</li> </ul> <button @click="addItem">add Item</button> </div> </template>
现在,每当我单击添加项目按钮时,它都会立即添加所有名称,这显然不是我想要的行为,我想一次添加一个名称。 提前致谢
这个小提琴显示了一种实现方式
new Vue({
el: '#app',
data(){
return {
names: ['Obama','kenedy','lincolen','bush'],
funnyPeople: ['Donald Duck','Tom','Jerry','Donald Trump']
}
},
methods: {
addItem(){
if(this.funnyPeople.length > 0) {
this.names.push(this.funnyPeople[0])
this.funnyPeople.shift();
}
}
}
})
首先,您应该将funnyPeople作为prop存储在data选项中,并且不要在每次访问addItem方法时都重新声明它。
我的方法从funnyPeople数组中获取第一个元素,将其推入names数组,然后将其从funnyPeople数组中删除。
这只是多种方法之一。
您可以简单地使用funnyPeople[0]
来funnyPeople[0]
数组的第一个元素,然后始终使用funnyPeople.splice(0, 1)
来对数组进行funnyPeople.splice(0, 1)
。 这种方法的缺点是最后您有一个空数组,因此您必须检查数组的长度。 此外,如果您的数组较大,这可能会很慢,因为每次都必须重新创建该数组。 或者,您可以使用在每次迭代中递增的索引。
使用arr.slice()
和其他数据。
export default {
data(){
return {
names: ['Obama','kenedy','lincolen','bush'],
count: 0
}
},
methods: {
addItem(){
let funnyPeople = ['Donald Duck','Tom','Jerry','Donald Trump']
if(this.count < funnyPeople.length) {
let addItem = funnyPeople.slice(this.count, this.count + 1);
this.names.push(addItem[0]);
this.count++
} else {
console.log('all items are added');
return true;
}
}
}
}
而且,如果您在数据中声明finalArray而不是在方法内部进行操作,请使用arr.splice()
:
export default {
data(){
return {
names: ['Obama','kenedy','lincolen','bush'],
funnyPeople: ['Donald Duck','Tom','Jerry','Donald Trump']
}
},
methods: {
addItem(){
if(this.funnyPeople.length) {
let addItem = funnyPeople.splice(0, 1);
this.names.push(addItem[0]);
} else {
console.log('all items are added');
return true;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.