我有一個場景,我在單擊按鈕時從網格中選擇元素后觸發按鈕單擊事件我需要從當前模式/網格中洗掉該元素
CheckedNames:["a","b","c"],
CheckedNamesId:[1,2,3],
DeletefromArray(){
this.CheckedNames.forEach(element => {
this.deleteItem(this.CheckedNamesId,this.CheckedNamesId.length);
});
},
deleteItem(index,length) {
this.List.splice(index, length)
},
check: function(e,row) {
this.CheckedNamesId.push(row.id)
console.log(this.CheckedNamesId)
},
現在,如果我通過復選框選擇“a”、“b”、“c”,我需要將它從陣列中洗掉,
uj5u.com熱心網友回復:
如果我理解正確,請嘗試以下代碼段:
new Vue({
el: '#demo',
data() {
return {
names: [{id: 1, name: 'a'},{id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}, {id: 5, name: 'e'}, {id: 6, name: 'f'}, {id: 7, name: 'g'}],
checkedNames: []
}
},
methods: {
check(item) {
if (!this.checkedNames.length || !this.checkedNames.find(f => item.id === f.id)) {
this.checkedNames.push(item)
} else {
this.checkedNames = this.checkedNames.filter(f => item.id !== f.id)
}
},
del() {
this.names = this.names.filter(a => !this.checkedNames.includes(a))
this.checkedNames = []
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<ul>
<li v-for="item in names" :key="item.id">
{{ item.name }}
<input type="checkbox" @click="check(item)" />
</li>
</ul>
<button @click="del">Delete</button>
</div>
uj5u.com熱心網友回復:
您可以嘗試像下面的代碼。在 List 陣列中回圈時,使用 indexof 檢查元素的 id 是否存在于 checkedNameID 陣列中。如果存在,則在回圈外定義的陣列中添加該元素的索引。然后您可以使用陣列中的另一個回圈將其切片。當您切片使用 1 作為第二個引數時,它將在回圈中一次洗掉 1 個元素。
const arr = []
deleteFromArray(){
this.List.forEach((element,index) => {
if(this.checkedNameID.indexOf(element.id) !== -1){
this.arr.push(index);
}
});
arr.forEach(item => {
this.List.splice(index,1);
}
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380333.html
標籤:javascript Vue.js
