在使用vantweap做勾选框是,遇到了一个奇葩问题,结果如下
\
代码如下:
<template>
<view>
<van-checkbox-group
value="{{ result }}"
bind:change="onChange"
>
<repeat
wx:for="{{arr}}"
wx:key="index"
wx:for-item="item"
>
<van-checkbox name="{{item}}">复选框{{item}}
<van-button
data-id='{{index}}'
@click="delbox"
>删除</van-button>
</van-checkbox>
</repeat>
</van-checkbox-group>
</view>
</template>
<script>
import wepy from 'wepy';
export default class Demo extends wepy.page {
components = {};
data = {
arr: [1, 2, 3, 4],
user: {},
telphone: {},
result: ['1', '2', '3', '4']
};
methods = {
onChange(e) {
this.result = e.detail;
},
delbox(e) {
this.arr.splice(Number(e.currentTarget.dataset.id), 1); // 源码中的this.children
this.result.splice(Number(e.currentTarget.dataset.id), 1); // 源码中的this.data
}
};
onload() {
}
}
</script>
看到这里整个人都不淡定了,打了断点到vant组件里面,发现源码中的this.data的value提前变化了,导致child的value值变成了false(value为true时为勾选状态,false时为未选中状态),此时我想到我把this.data的赋值改为异步,但是发现还是有问题,最后是van-checkbox-group的change方法执行了,导致失效
checkbox-group源码:
import { useChildren } from '../common/relation';
import { VantComponent } from '../common/component';
VantComponent({
field: true,
relation: useChildren('checkbox', function (target) {
this.updateChild(target);
}),
props: {
max: Number,
value: {
type: Array,
observer: 'updateChildren',
},
disabled: {
type: Boolean,
observer: 'updateChildren',
},
},
methods: {
updateChildren() {
this.children.forEach((child) => this.updateChild(child));
},
updateChild(child) {
const { value, disabled } = this.data;
child.setData({
value: value.indexOf(child.data.name) !== -1,
parentDisabled: disabled,
});
},
},
});
修改后的代码如下:
<!--
* @Author: your name
* @Date: 2021-05-21 14:53:09
* @LastEditTime: 2021-07-01 11:33:33
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \wx-magpie-mall\src\pages\demo.wpy
-->
<template>
<view>
<van-checkbox-group
value="{{ result }}"
bind:change="onChange"
>
<repeat
wx:for="{{arr}}"
wx:key="index"
wx:for-item="item"
>
<van-checkbox name="{{item}}">复选框{{item}}
<van-button
data-id='{{index}}'
@click="delbox"
>删除</van-button>
</van-checkbox>
</repeat>
</van-checkbox-group>
</view>
</template>
<script>
import wepy from 'wepy';
export default class Demo extends wepy.page {
components = {};
data = {
arr: [1, 2, 3, 4],
status: true, // 1、控制change方法是否执行
result: ['1', '2', '3', '4']
};
methods = {
onChange(e) {
if (this.status) {
this.result = e.detail;
} else {
this.status = true;
}
},
delbox(e) {
this.status = false;
this.arr.splice(Number(e.currentTarget.dataset.id), 1);
// 2、this.data赋值变异步
setTimeout(() => {
this.result.splice(Number(e.currentTarget.dataset.id), 1);
}, 0);
}
};
onload() {
}
}
</script>