checkbox.vue
3.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
<template>
<label class="v-checkbox-wrapper" :style="{'display':displayType}">
<span :class="checkboxClasses">
<input
class="v-checkbox-input"
type="checkbox"
:value="label"
v-model="model"
@change="change"
/>
<span class="v-checkbox-inner"></span>
</span>
<span><slot v-if="showSlot">{{ label }}</slot></span>
</label>
</template>
<script>
import utils from '../../src/utils/utils.js'
export default{
name: 'v-checkbox',
props: {
value: {
type: [String, Number, Boolean]
},
// use in checkbox-group
label: {
type: [String, Number],
require: true
},
disabled: Boolean,
// partial selection effect
indeterminate: Boolean,
showSlot:{
type:Boolean,
default:true
}
},
data(){
return {
model: this.value,
_checkboxGroup: {}
}
},
computed: {
checkboxClasses(){
return [
'v-checkbox',
{
['v-checkbox-checked']: this.model,
['v-checkbox-disabled']: this.disabled,
['v-checkbox-indeterminate']: this.indeterminate,
}
]
},
isCheckBoxGroup() {
this._checkboxGroup = utils.getParentCompByName(this, 'v-checkbox-group');
return this._checkboxGroup ? true : false;
},
// 是否横向显示还是纵向显示
displayType(){
var style = 'inline-block';
if (this._checkboxGroup) {
style = this._checkboxGroup.isVerticalShow ? 'block' : 'inline-block';
}
return style;
},
},
methods: {
change (event) {
if (this.disabled) {
this.model = !this.model;
return false;
}
const checked = event.target.checked;
this.$emit('input', checked);
this.$emit('change');
if (this.isCheckBoxGroup) {
this._checkboxGroup.updateModel(this.label, checked);
}
},
initModel(){
if (this.isCheckBoxGroup) {
let checkboxGroup = this._checkboxGroup;
if (Array.isArray(checkboxGroup.value) && checkboxGroup.value.length > 0) {
if (checkboxGroup.value.indexOf(this.label) > -1) {
this.model = true;
}
}
} else {
this.model = this.value;
}
},
// 通过单选更新 model
updateModelBySingle(){
if (!this.disabled){
this.model = this.value;
}
},
// 父组件调用更新 model
updateModelByGroup(checkBoxGroup){
if (checkBoxGroup.indexOf(this.label) > -1) {
if (!this.disabled){
this.model = true;
}
}else{
if (!this.disabled){
this.model = false;
}
}
}
},
created(){
this.initModel();
},
watch: {
'value'(val){
this.updateModelBySingle();
}
}
}
</script>