我使用 Vue.js 组件创建了简单的搜索。问题是我不知道如何选择特定的复选框。现在我正在将所有选定的对象收集到数组中,并在必要时删除它们。
这是我所做的:
<template>
<div class="list" v-if="is_opened">
<div v-if="is_title_presented" class="list-title">
{{title}}
<i class="material-icons list-close-icon" @click="is_opened = false">clear</i>
</div>
<div class="list-item-container">
<div class="searchBarMain">
<input type="text" name="header-search" value="" id="searchBarInput" placeholder="Otsi kasutajat..." v-model="searchText">
</div>
<div class='list-item' v-for="(item, index) in filteredCustomers" :key="item.name" @click="$_test(item)">
<div class="list-cell">
<div class="list-item-icon">
<avatar :avatar_presented="item.avatar" :avatar="item.avatar" :name="item.name"></avatar>
</div>
<div class="list-item-text">
{{ item.name }}
</div>
<div class="list-item-selection" style="float: right;">
<input id="item.id" name="list-checkbox" type="checkbox" v-model="item.id" :checked="true">
</div>
</div>
</div>
</div>
</div>
</template>
逻辑是这样的:
data () {
return {
searchText: '',
is_selected: false,
items: [{avatar: '', name: 'John'}],
filtered_items: [],
selected_items: []
}
},
methods: {
$_test: function (item) {
if (this.selected_items.includes(item)) {
#Here I have to uncheck the selected item's checkbox and remove it from array
console.log('Exists')
this.selected_items.splice(this.selected_items.indexOf(item), 1)
} else {
#Here I have to check the selected item's checkbox and add it to the array
console.log('Not existing')
this.selected_items.push(item)
}
}
},
computed: {
filteredCustomers:function() {
var self=this;
return this.items.filter(
function(item) {
return item.name.toLowerCase().indexOf(self.searchText.toLowerCase())>=0;
});
}
}
对象收集方法是达到预期效果的好方法吗?
你能不能在你的元素对象中添加一个selected
或checked
键?之后您可以将其 v-model 到输入上并检查检查了哪些元素。
https://codesandbox.io/s/9j3zk6o49o
改变了 html
<div class="list-item-selection" style="float: right;">
<input @change="$_test()" id="item.id" name="list-checkbox" type="checkbox" v-model="item.selected" :key="item.id">
</div>
脚本已更改
data() {
return {
searchText: "",
is_selected: false,
items: [
{
id: 0,
avatar: "",
name: "Tarvo",
selected: true
},
{ id: 1, avatar: "", name: "Lennart" },
{
id: 2,
avatar: "",
name: "Sven",
selected: true
},
{
id: 3,
avatar: "",
name: "Jaanus",
selected: false
},
{
id: 4,
avatar: "",
name: "Rain",
selected: false
}
],
filtered_items: [],
selected_items: []
};
},
methods: {
$_test: function(item) {
let selected = this.items.filter(item => item.selected);
console.log(selected);
},
$_removeTag: function(index) {
this.selected_items.splice(index, 1);
}
},
我是一名优秀的程序员,十分优秀!