vue构建动态表单的方法示例

2020-06-14 06:21:27易采站长站整理

data () {
return {
currentValue: this.value
};
},
methods: {
onInputEvent(value) {
this.$emit('input', this.name, value);
},
reset() {
this.currentValue = "";
}
},
watch: {
value (val) {
this.currentValue = val;
}
}
};

然后我们的下拉框组件就可以少写一些共用的代码,直接用 mixins: [formMixins]


<template>
<el-form-item :label="label">
<el-select v-model="currentValue" @input="onInputEvent">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</el-form-item>
</template>

<script>
import formMixins from '../../../mixins/form-model'
export default {
name: "SelectList",
props: ['name', 'label', 'value', 'options'],
mixins: [formMixins],
data() {
return {
currentValue: this.value
}
}
}
</script>

动态生成表单

这里主要是根据配置的数据,循环生成表单组件。默认提供提交和重置按钮,如果不需要可以通过slot传递其他操作按钮。这里的要点主要有:

监听表单组件的数据变化:

每个表单组件都有一个name标识它的业务含义,绑定的数据也是formData[field.name],@input事件传递updateForm,在updateForm里面更新this.formData[name],保证了this.formData里面的数据是和表单组件选择/填写的内容一致。

重置时改变表单组件的数据:

因为组件内部会监听父元素的value,所以这里只要清空this.formData的值,组件内部的数据也会跟着清空。


<template>
<div>
<el-form :inline="true" ref="form" :model="formData" class="demo-form-inline">
<el-col :span="field.cols" v-for="(field, index) in config.fieldsConfig" v-bind:key="index">
<component :key="index"
:is="field.fieldType"
:label="field.label"
:value="formData[field.name]"
:multiple="field.multiple"
@input="updateForm"
v-bind="field"
:options="field.options"
:ref="field.name"
>
</component>
</el-col>
<slot name="buttons">
<el-button type="primary" @click="submit" size="small">{{onSubmitText}}</el-button>
<el-button type="default" @click="reset" size="small">{{onResetText}}</el-button>
</slot>
</el-form>
</div>
</template>
<script>
import SelectList from './basicComponent/SelectList'
import TextInput from './basicComponent/TextInput'