持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第15天,点击查看活动详情
小程序实现列表复选,点击全选按钮,全选列表。保存数据,去重数据,最近项目中有一个需求是题库选题,在题库中选中数据,需要把数据存下来,点击确定按钮,返回上一页的时候把数据带过去。
最开始想的是,点击复选的时候,只存id数组,最后点保存的时候,遍历数据,把整个题存数据。这样会有一个问题,就是,列表是滚动加载的,我返回上一个页面,再点进来的时候需要回显数据,但是只加载了一页的数据,就会出现问题了
所以就每次点击的时候就把数据存下。需要做的就是去重的操作,一起看看吧
html代码
<view class="d-fx-s">
<van-checkbox checked-color="#fb8337" value="{{ checkedAll}}" bind:change="checkedAll" shape="square"
icon-size="30rpx" disabled="{{!questions.length}}">
</van-checkbox><text class="m-l-20">已选:{{result.length || 0}}</text>
</view>
<van-checkbox-group value="{{result}}" bind:change="onChange">
<van-cell-group wx:if="{{showCell}}">
<van-cell class="card-item d-fx-s" wx:for="{{list}}" wx:key="index" value-class="value-class" clickable
bind:click="toggle">
<van-checkbox catch:tap="noop" class="checkboxes-{{ index }} m-r-20"
name="{{ item.id }}&{{tabType}}" shape="square" checked-color="#FB8337" icon-size="30rpx"
wx:if="{{!item.layer}}" />
<view slot="title" data-id="{{item.id}}" class="cell">
</view>
</van-cell>
</van-cell-group>
</van-checkbox-group>
</view>
点击checkbox按钮,选中,取消
// checkbox选择
toggle(event) {
const {
index
} = event.currentTarget.dataset;
const checkbox = this.selectComponent(`.checkboxes-${index}`);
checkbox && checkbox.toggle();
},
点击列操作数据,需要去重
// 单个选择数据
onChange(event) {
let newResult = event.detail;
let oldResult = this.data.result;
if (oldResult.length < newResult.length) { // 新增
let diff = this.getDiff(newResult, oldResult),
id = '';
if (diff.length) {
id = diff[0].split('&')[0];
}
let ques = this.data.list.filter(item => {
return item.id == id;
})
this.data.questions.push(ques[0]);
} else {
let diff2 = this.getDiff(oldResult, newResult),
id2 = '';
if (diff2.length) {
id2 = diff2[0].split('&')[0];
}
this.data.questions.length && this.data.questions.forEach((item, i) => {
if (item.id == id2) {
this.data.questions.splice(i, 1);
}
})
}
this.setData({
result: newResult,
disabled: this.data.result.length == 0,
checkedAll: this.data.result.length == this.data.list.length && this.data.result.length !== 0,
questions: this.data.questions,
});
},
监听点击全选按钮事件
// 监听全选
checkedAll() {
this.setData({
checkedAll: !this.data.checkedAll
})
let result = this.data.result || [],
questions = this.data.questions;
if (this.data.checkedAll) {
this.data.list.forEach(item => {
if (!item.layer) {
result.push(item.id + '&' + this.data.tabType);
questions.push(item);
}
})
}
this.setData({
result: result || [],
questions: questions,
})
},
设置全选按钮的选中状态
// 设置全选按钮状态
setAllStatus() {
let len = this.data.result.length;
let newLen = 0;
this.data.list.length && this.data.list.forEach(item => {
if (!item.layer) {
newLen++
}
})
this.setData({
checkedAll: len == newLen && len !== 0
})
},