-
Notifications
You must be signed in to change notification settings - Fork 375
/
mpx-checkbox-group.vue
91 lines (89 loc) · 2.33 KB
/
mpx-checkbox-group.vue
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
<script>
import getInnerListeners from '@mpxjs/webpack-plugin/lib/runtime/components/web/getInnerListeners'
function travelSlot (slot, effect) {
if (slot) {
slot.forEach((VNode) => {
effect && effect(VNode)
if (VNode.children) {
travelSlot(VNode.children, effect)
}
})
}
}
export default {
name: 'mpx-checkbox-group',
props: {
name: String,
value: {
type: Array,
default () {
return []
}
}
},
render (createElement) {
const data = {
class: 'mpx-checkbox-group',
on: getInnerListeners(this),
}
return createElement('div', data, this.$slots.default)
},
mounted () {
// 为了建立正确的绑定关系,初始时无论有没有value都需要遍历一次slot
if (this.value.length) {
this.setValue(this.value)
} else {
this.getValue()
}
},
methods: {
getValue () {
const value = []
travelSlot(this.$slots.default, (VNode) => {
if (VNode.tag && VNode.tag.endsWith('mpx-checkbox')) {
const el = VNode.elm
const component = VNode.componentInstance
if (component) {
if (!component.group) {
component.group = this
}
if (component.group === this && el && el.checked && el.value) {
value.push(el.value)
}
}
}
})
return value
},
setValue (value) {
travelSlot(this.$slots.default, (VNode) => {
if (VNode.tag && VNode.tag.endsWith('mpx-checkbox')) {
const el = VNode.elm
const component = VNode.componentInstance
if (component) {
if (!component.group) {
component.group = this
}
if (component.group === this && el && el.value) {
el.checked = value.indexOf(el.value) !== -1
}
}
}
})
},
notifyChange (value) {
if (value !== undefined) {
this.setValue(value)
} else {
value = this.getValue()
}
this.$emit('change', {
type: 'change',
detail: {
value: value
}
})
}
}
}
</script>