
show1.jpg
三種狀態(tài)的勾選框
日常開發(fā)中,我們經(jīng)常使用勾選框,無非是兩種狀態(tài):選中、未選中;
本文的組件,實現(xiàn)三種狀態(tài):未選中、半選、已選中;
通過案例,感受vue中 model 的使用場景
調(diào)用效果及代碼
不斷點擊勾選框,在未選中、半選、已選中三種狀態(tài)之間切換

show2.gif
<!--
* @Date: 2022-05-24 10:11:48
* @Author: surewinT 840325271@qq.com
* @LastEditTime: 2022-05-24 11:08:26
* @LastEditors: surewinT 840325271@qq.com
* @Description: 調(diào)用頁面
-->
<template>
<div class="">
<p-three-checkbox :data="checkboxData" v-model="value" />
</div>
</template>
<script>
import PThreeCheckbox from '@/components/p-three-checkbox';
export default {
components: {
'p-three-checkbox': PThreeCheckbox,
},
props: [],
data() {
return {
checkboxData: {
label: '哈哈哈',
disabled: false,
},
value: 0,
};
},
mounted() {},
watch: {
value() {
console.log('變化了:', this.value);
},
},
methods: {},
};
</script>
<style lang='scss' scoped>
</style>
組件源碼
model 可以設(shè)置 v-model 的綁定值,使用數(shù)據(jù)雙向傳遞;
用 num 記錄勾選,在0、1、2三種狀態(tài)間,來回切換;
<!--
* @Author: surewinT 840325271@qq.com
* @LastEditTime: 2022-05-24 10:52:13
* @LastEditors: surewinT 840325271@qq.com
* @Description: '具備三個狀態(tài)'的勾選框組件
-->
<template>
<span class="stateCheckBox">
<el-checkbox
v-model="check"
:indeterminate="mid"
:disabled="data.disabled"
@change="change"
>
<span
class="label"
:class="[check ? 'active' : '', data.disabled ? 'disabled' : '']"
>{{ data.label }}</span
>
</el-checkbox>
</span>
</template>
<script>
/**
* @description: props 說明
* data {
* label: 顯示的值,
* disabled:是否禁用
* }
*/
export default {
components: {},
model: {
prop: 'value',
event: 'input',
},
props: {
value: {
type: Number,
default: 0,
},
data: {
type: Object,
default: () => {
return {};
},
},
},
data() {
return {
check: false,
mid: false,
num: 0,
};
},
mounted() {
this.loadState(this.value);
},
watch: {
num() {
this.$emit('input', this.num);
},
},
methods: {
// 初始化狀態(tài)
loadState(num) {
this.num = Number(num);
this.chooseState(this.num);
},
// 改變狀態(tài)
chooseState(num) {
this.check = num == 2 ? true : false;
this.mid = num == 1 ? true : false;
},
// 點擊多選框
change() {
this.num++;
this.num > 2 ? (this.num = 0) : '';
this.chooseState(this.num);
},
},
};
</script>
<style lang="scss" scoped>
.stateCheckBox {
margin-right: 30px;
.label {
color: #606266;
}
.active {
color: #409eff;
}
.disabled {
color: #c0c4cc;
}
}
</style>
倉庫源碼
后續(xù)補充