-
Notifications
You must be signed in to change notification settings - Fork 375
/
mpx-form.vue
90 lines (86 loc) · 2.31 KB
/
mpx-form.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
<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)
}
})
}
}
function getFormValue (slot, effect) {
const value = {}
travelSlot(slot, (VNode) => {
effect && effect(VNode)
if (VNode.tag) {
const el = VNode.elm
const component = VNode.componentInstance
if (component && component.name && component.getValue) {
value[component.name] = component.getValue()
} else if (el && el.name && el.value !== undefined) {
value[el.name] = el.value
}
}
})
return value
}
function setFormValue (slot, value) {
travelSlot(slot, (VNode) => {
if (VNode.tag) {
const el = VNode.elm
const component = VNode.componentInstance
if (component && component.name && component.notifyChange) {
component.notifyChange(value[component.name])
} else if (el && el.name && el.value !== undefined) {
el.value = value[el.name]
}
}
})
}
export default {
name: 'mpx-form',
render (createElement) {
const data = {
class: 'mpx-form',
on: getInnerListeners(this),
}
return createElement('div', data, this.$slots.default)
},
mounted () {
this.initialValue = getFormValue(this.$slots.default, (VNode) => {
if (VNode.tag && VNode.tag.endsWith('mpx-button')) {
const component = VNode.componentInstance
if (component && component.formType) {
if (!component.form) {
component.form = this
}
}
}
})
},
methods: {
submit () {
const value = getFormValue(this.$slots.default)
this.$emit('submit', {
type:'submit',
detail: {
value
},
formId: ''
})
},
reset () {
setFormValue(this.$slots.default, this.initialValue)
this.$emit('reset', {
type:'reset',
detail: {
value: this.initialValue
},
formId: ''
})
}
}
}
</script>