Vue实现单选、全选、反选
<template><div><div><input type="checkbox" v-model="checkAll" />全选</div><div><input type="checkbox" @change="inverse" />反选</div><div class="fruit" v-
·
<template>
<div>
<div><input type="checkbox" v-model="checkAll" />全选</div>
<div><input type="checkbox" @change="inverse" />反选</div>
<div class="fruit" v-for="(item, index) in fruits" :key="index">
<input type="checkbox" v-model="model" :value="item.value"/>
{{ item.label }}
</div>
<div>已选择:{{ model }} 总价:{{total}}</div>
</div>
</template>
<script>
export default {
data() {
return {
fruits: [
{
label: "Apple",
value: "apple",
price: 2.5,
},
{
label: "Banana",
value: "banana",
price: 3,
},
{
label: "Cherry",
value: "cherry",
price: 5,
},
{
label: "Orange",
value: "orange",
price: 1.5,
},
],
model: [],
};
},
methods: {
inverse() {
this.fruits.forEach(fruit=>{
let index = this.model.findIndex((item) => item === fruit.value);
if (index > -1) {
this.model.splice(index, 1);
} else {
this.model.push(fruit.value);
}
})
},
},
computed: {
checkAll:{
get(){
this.model.length === this.fruits.length
},
set(val){
console.log(val)
if(val){
this.model=[]
this.fruits.forEach(item=>{
this.model.push(item.value)
})
}else{
this.model=[]
}
}
},
total() {
let t = 0;
this.model.forEach((item) => {
let index = this.fruits.findIndex((fruit) => fruit.value === item);
t += this.fruits[index].price;
});
return t;
},
},
};
</script>
<style lang="scss" scoped>
</style>
更多推荐
已为社区贡献6条内容
所有评论(0)