用vue实现多选框单选,全选和删除

包含功能:

  • 单选
  • 多选
  • 全选
  • 批量删除

实现原理:

  • fruits:决定显示元素的多少,所以,对元素增删改查都操作它
  • fruitIds: 通过对数组的增删改查,控制元素选中与否
  • isCheckedAll: 判断是否全选,如果全选,就把数组fruits中的id都添加给fruitIds

注意事项:
1、全选框中,:checked="fruits.length===fruitIds.length && fruitIds.length"的处理,是为了防止 数据和fruitIds都为空,却全选选中的情况
2、如果需要封装成组件,请把变量设置为属性props,把事件通过$.emit发射到父级
3、真正开发中,这里要用到vuex,axios处理真实数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<template>
<div>
<input type="checkbox"
class="input-checkbox"
:checked="fruits.length===fruitIds.length && fruitIds.length"
@click="checkedAll" />
<label>全选</label>
<div v-for="fruite in fruits"
:key="fruite.id"
class="fruiteList">
<input type="checkbox"
:checked="fruitIds.indexOf(fruite.id)>=0"
name="checkboxinput"
class="input-checkbox"
@click="checkedOne(fruite.id)">
<label>{{fruite.value}}</label>
</div>
<button @click="deleteSome">Delete</button>
</div>
</template>

<script>

export default {
data () {
return {
fruits: [{
id: '1',
value: '苹果'
}, {
id: '2',
value: '荔枝'
}, {
id: '3',
value: '香蕉'
}, {
id: '4',
value: '火龙果'
}],
fruitIds: ['1', '3', '4'],
// 初始化全选按钮, 默认不选
isCheckedAll: false
}
},
methods: {
checkedOne (fruitId) {
let idIndex = this.fruitIds.indexOf(fruitId)
if (idIndex >= 0) {//如果已经包含就去除
this.fruitIds.splice(idIndex, 1)
} else {//如果没有包含就添加
this.fruitIds.push(fruitId)
}
},
checkedAll (e) {
this.isCheckedAll = e.target.checked;
if (this.isCheckedAll) {//全选时
this.fruitIds = []
this.fruits.forEach(item => {
this.fruitIds.push(item.id)
})
} else {
this.fruitIds = []
}
},
deleteSome () {
this.fruits = this.fruits.filter(item => this.fruitIds.indexOf(item.id) === -1)
this.fruitIds = []
}
}
}
</script>
<style scoped lang="scss">
.input-checkbox {
width: 40px;
height: 40px;
-webkit-appearance: none;
position: absolute;
outline: none;
border: none;
&::after {
left: 0;
top: 0;
content: url("../assets/images/round.svg");
}
&:checked:after {
left: 0;
top: 0;
content: url("../assets/images/done.svg");
}
}
label {
padding-left: 50px;
height: 40px;
line-height: 45px;
}
</style>