最近公司有个需求是用checkBox的indeterminate和v-model展示三种不同状态:
1、未选中(indeterminate:false,v-model:false)代表未选;
2、半选中(indeterminate:true,v-model:false)代表待选;
1、未选中(indeterminate:false,v-model:true)代表已选;
html:
<el-checkbox :indeterminate="city[0]" v-model="city[1]" @change="handleCheckAllChange(idx)" v-for="(city,idx) in cities" :label="city" :key="idx">{{city}}{{idx}}</el-checkbox>
js:
const cityOptions = {city0:[false,true],city1:[false,false],city2:[false,false],city3:[false,false]};
var Main = {
data() {
return {
checkAll: false,
checkedCities: ['上海', '北京'],
cities: cityOptions,
isIndeterminate: true
};
},
methods: {
handleCheckAllChange(id) {
if (!this.cities[id][0] && this.cities[id][1]) { // 全选中
console.log('设置为未选中',this.cities[id])
this.$set(this.cities, id, [false, false])
} else if (!this.cities[id][0] && !this.cities[id][1]) { // 未选中
console.log('设置为半选中',this.cities[id])
this.$set(this.cities, id, [true, false])
} else if (this.cities[id][0] && !this.cities[id][1]) { // 半选中
console.log('设置为全选中',this.cities[id])
this.$set(this.cities, id, [false, true])
}
}
}
};
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
期望:
未选中、半选中、全选中循环打印,且不会出现元素值都为true的情况
结果:
求大佬指教,谢谢
1.checkBox在勾选的时候,会自动改变切换checkAll的值(不受状态控制),而indeterminate为true只会控制checkBox为半选中状态,所以出现了[true,true]这种情况。
2.全选中——>未选中,此时值为:[false,true],打印了:设置为未选中,[false,true]。然后通过$set设置为[false,false],点击的时候,checkBox自动将checkAll改变为true了,此时值为[false,true],再次进入全选中->未选中,再次打印:设置为未选中,[false,true]
另外:checkBox,应该根据需求设置indeterminate改变是否显示半选中状态,checkAll会根据点击自动改变