Vue 解决更改数组数据后不渲染问题
做checkbox多选功能的时候遇到了一个坑,逻辑怎么看都对,但是就是有bug,数组值已经改变,但页面勾选没有重新渲染。
解决方法
通过concat()方法为数组添加元素,splice()方法移除数组元素
示例:
<template>
<view class="padding-top-xl">
<cu-custom bgColor="bg-gradual-blue" :isBack="false"><block slot="backText"></block><block slot="content">test</block></cu-custom>
<view class="padding-top-sm" v-for="(item,index) in peopleModelList" :key="index">
<view class="cu-form-group solid-bottom">
<view class="title">{{item.peopleName}}</view>
<view class="text-gray text-sm">
<view>{{item.phone}}</view>
</view>
<checkbox-group @change="checkPeople" :id="item.peopleId">
<checkbox class='round' :checked="checkIdList.indexOf(item.peopleId) != -1 ? true : false " :value="item.peopleId"></checkbox>
</checkbox-group>
</view>
</view>
<view class="padding flex flex-direction">
<button @tap="allCheck" class="cu-btn bg-blue lg">全选</button>
<button @tap="removeCheck" class="cu-btn bg-red margin-tb-sm lg">取消选中</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
peopleModelList:[
{
peopleId:1,
peopleName:'张一',
phone:'18888888881',
},
{
peopleId:2,
peopleName:'张二',
phone:'18888888882',
},
{
peopleId:3,
peopleName:'张三',
phone:'18888888883',
},
{
peopleId:4,
peopleName:'张四',
phone:'18888888884',
},
{
peopleId:5,
peopleName:'张五',
phone:'18888888885',
}
],
checkIdList:[]
}
},
methods: {
checkPeople(e){
console.log(e)
this.checkIdList = this.checkIdList.concat(parseInt(e.detail.value[0])) //动态将值加入数组(注意转为int,亲测字符无效)
console.log(this.checkIdList)
},
removeCheck(){
this.checkIdList.splice(0,this.checkIdList.length) //清空数组
console.log(this.checkIdList)
},
allCheck(){
for(var i =0;i<this.peopleModelList.length;i++){
this.checkIdList = this.checkIdList.concat(this.peopleModelList[i].peopleId)
}
console.log(this.checkIdList)
}
}
}
</script>
<style>
</style>