单选多选全选是我们开发中经常会用到的功能,刚开始接触vue的时候也可以通过单选多选小功能的实现来更好的了解 vue 带来的方便便捷
<template>
<view class="content">
<!-- 单选 -->
<view class="onlybtn">
<text v-for="(item,index) in onlyList" :key="index" :class="ind==index?'btn active':'btn'"
@click="changeonly(index)">{{item}}</text>
</view>
<!-- 多选 -->
<view class="morebtn">
<text v-for="(item,index) in moreList" :key="index" :class="changeMore.includes(item)?'btn active':'btn'"
@click="changemore(item)">{{item}}</text>
</view>
<view>
<view class="allchange" @click="allchange">
<text :class="changeMore.length==moreList.length?'active circle':'circle'"></text>
<text>全选</text>
</view>
<text>未全选中状态下,点击全选 多选中的按钮全部选中 再次点击取消</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
// 单选
onlyList: ['租房', '买房', '卖房'],
ind: 0,
// 多选全选
moreList: ['出行', '医疗', '住房', '吃喝'],
changeMore: []
}
},
methods: {
// 单选
changeonly(ind) {
this.ind = ind
},
// 多选
changemore(item) {
if (this.changeMore.includes(item)) {
this.changeMore.splice(this.changeMore.indexOf(item), 1)
} else {
this.changeMore.push(item)
}
},
// 全选
allchange() {
if (this.changeMore.length == this.moreList.length) {
this.changeMore = []
} else {
this.changeMore = Object([],this.moreList)
}
// 开始写没多想出 出现了小错误
// if (this.changeMore.length == this.moreList.length) {
// this.changeMore = []
// } else {
// this.changeMore = this.moreList
// }
}
}
}
</script>
<style>
.btn {
display: inline-block;
margin-top: 10rpx;
margin-left: 20rpx;
border: 1rpx solid #ccc;
padding: 5rpx 20rpx;
}
.btn.active {
background-color: lightblue;
}
.allchange {
display: flex;
align-self: baseline;
}
.circle {
display: inline-block;
width: 30rpx;
height: 20rpx;
border: 1rpx solid #ccc;
color: #fff;
margin: 10rpx;
border-radius: 50%;
}
.circle.active {
background-color: lightblue;
}
button {
margin: 20rpx;
}
</style>
以上逻辑实现了小功能但是再开始的时候没注意出现了小错误
// 开始写没多想出 出现了小错误
// if (this.changeMore.length == this.moreList.length) {
// this.changeMore = []
// } else {
// this.changeMore = this.moreList
// }
为什么不能这样直接等于呢?
两个对象a,b如果直接a = b ,在a发生改变时候 b也跟着发生改变。因为直接将b赋值给a,b与a就会指向同一个地址,就会导致a发生变化的时候b也发生变化 可以用Object.assign() 来解决。也可以将b中的对象循环放入a中