vue 动态表单
一、动态表单
-
数据集
1、原始数据集
var json = " [ { \"key\":\"id\", \"text\":\"id\" }, { \"key\":\"name\", \"text\":\"姓名\" }, { \"key\":\"age\", \"text\":\"年龄\" } ]";
2、表单数据集
var data = JSON.parse(json); // 遍历数据 data.forEach((element) => { // vue data this.fromData.push({ field: element.key, text: element.value, value: null, }); });
-
渲染表单
<template> <el-dialog :title="form" visible="true"> <el-form ref="dataForm" :rules="rules" :model="formData" label-position="left" label-width="70px" style="width: 400px; margin-left: 50px" > <el-form-item v-for="item in formData" :key="item.field" :prop="item.field" :label="item.text" > <el-input v-model="item.value" :id="item.key" /> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="dialogFormVisible = false"> 取消 </el-button> <el-button type="primary" @click="createData()"> 确定 </el-button> </div> </el-dialog> </template>
-
表单提交
createData() { // 接收数据 var raw = {}; // 遍历数据 this.formData.forEach((item) => { raw[item.field] = item.value; }); // 打印数据 console.log(raw); },
-
完整代码
<template> <!--对话框--> <el-dialog :title="form" visible="true"> <!--表单--> <el-form ref="dataForm" :rules="rules" :model="formData" label-position="left" label-width="70px" style="width: 400px; margin-left: 50px" > <!--添加表单元素--> <el-form-item v-for="item in formData" :key="item.field" :prop="item.field" :label="item.text" > <el-input v-model="item.value" :id="item.key" /> </el-form-item> </el-form> <!--表单提交--> <div slot="footer" class="dialog-footer"> <el-button @click="dialogFormVisible = false"> 取消 </el-button> <el-button type="primary" @click="createData()"> 确定 </el-button> </div> </el-dialog> </template> <!--script--> <script> export default { name: "form", data() { return { formData: [], }; }, created() { this.getFormData(); }, methods: { // 加载表单数据 getFormData() { var json = ` [ { \"key\":\"id\", \"text\":\"id\" }, { \"key\":\"name\", \"text\":\"姓名\" }, { \"key\":\"age\", \"text\":\"年龄\" } ]`; var data = JSON.parse(json); // 遍历数据 data.forEach((element) => { // vue data this.formData.push({ field: element.key, text: element.text, value: null, }); }); }, createData() { // 接收数据 var raw = {}; // 遍历数据 this.formData.forEach((item) => { raw[item.field] = item.value; }); // 打印数据 console.log(raw); }, }, }; </script>
-
效果
-
待续
如有帮助,欢迎转载,转载请注明原文链接:https://www.cnblogs.com/study10000/p/18228378