console
var vm = new Vue({
el: '#app',
data: {
dynamicForm: [
{
title: '姓名',
field: 'name',
type: 'text',
tips: '请输入姓名',
options: [],
rules: ['required', 'min:3', 'max:5'],
value: ''
},
{
title: '性别',
field: 'gender',
type: 'radio',
tips: '',
options: [
{
text: '男生',
value: 1
},
{
text: '女生',
value: 2
}
],
rules: ['required', 'min:3', 'max:5'],
value: ''
},
{
title: '出生日期',
field: 'birthday',
type: 'date',
tips: '请选择出生日期',
options: [],
rules: ['required', 'min:3', 'max:5'],
value: ''
}
]
},
methods: {
submit:function() {
alert(JSON.stringify(this.getFormResultToObject()))
},
getFormResultToObject: function() {
let result = {}
for (let i=0; this.dynamicForm.length> i; i++) {
let formItem = this.dynamicForm[i]
result[formItem.field] = formItem.value
}
return result;
}
}
})
<div id="app">
<div class="dynamic-form">
<div class="form-item" v-for="formItem in dynamicForm" :key="formItem.field">
<template v-if="formItem.type == 'text'">
<div class="form-item__label">
{{ formItem.title }}:
</div>
<div class="form-item__control">
<input type="text" v-model="formItem.value" :placeholder="formItem.tips" />
</div>
</template>
<template v-else-if="formItem.type == 'radio'">
<div class="form-item__label">
{{ formItem.title }}:
</div>
<div class="form-item__control">
<div v-for="opt in formItem.options" :key="opt.value">
<input type="radio"
v-model="formItem.value"
:value="opt.value">
<label>{{ opt.text }}</label>
</div>
</div>
</template>
<template v-else-if="formItem.type == 'date'">
<div class="form-item__label">
{{ formItem.title }}:
</div>
<div class="form-item__control">
<input type="date" v-model="formItem.value" :placeholder="formItem.tips" />
</div>
</template>
</div>
</div>
<button type="button" @click="submit">提交</button>
</div>