[英]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.