Web Front-end
JS Tutorial
Vue+ElementUI method to realize dynamic rendering and visual configuration of formsVue+ElementUI method to realize dynamic rendering and visual configuration of forms
This article mainly introduces the method of Vue ElementUI to realize dynamic rendering and visual configuration of forms. Friends who need it can refer to it
Dynamic rendering means having asynchronous data, which probably looks like this:
{
"inline": true,
"labelPosition": "right",
"labelWidth": "",
"size": "small",
"statusIcon": true,
"formItemList": [
{
"type": "input",
"label": "姓名",
"disable": false,
"readonly": false,
"value": "",
"placeholder": "请输入姓名",
"rules": [],
"key": "name",
"subtype": "text"
},
{
"type": "radio",
"label": "性别",
"value": "",
"button": false,
"border": true,
"rules": [],
"key": "gender",
"options": [
{
"value": "1",
"label": "男",
"disabled": false
},
{
"value": "0",
"label": "女",
"disabled": false
}
]
}
]
} Then you need to render this json like this:
The data of the final submitted form looks like this:
{
"name": "Genji",
"gender": "1"
}Then our goal is to encapsulate such a Component:
<dynamic-form :config="someConfig" v-model="someData" />
Implementation
Before you start, you need to know how v-model works:
<input v-model="something">
This is nothing more It is syntactic sugar for the following example:
<input :value="something" @input="something = $event.target.value">
After understanding this, let’s implement this component step by step.
First, forward the configuration to el-form:
<template>
<el-form
class="dynamic-form"
:inline="formConfig.inline"
:model="value"
:label-position="formConfig.labelPosition"
:label-width="formConfig.labelWidth"
:size='formConfig.size'
:status-icon="formConfig.statusIcon">
<slot/>
</el-form>
</template>
<script>
export default {
props: {
formConfig: {
type: Object,
required: true
},
value: {
type: Object,
required: true
}
},
}
</script>The second step, set the default value.
Because each form-item will require a v-model, so before rendering, ensure that each field has a value. One thing to note here is that the prop passed in by the parent component should not be directly modified within the component, so we use {...this.value} to quickly make a copy, and finally don’t forget to notify the parent component. The code is as follows:
export default {
props: {
formConfig: {...},
value: {...},
},
methods: {
setDefaultValue() {
const formData = { ...this.value }
// 设置默认值
this.formConfig.formItemList.forEach(({ key, value }) => {
if (formData[key] === undefined || formData[key] === null) {
formData[key] = value
}
})
this.$emit('input', formData)
}
},
mounted() {
this.setDefaultValue()
},
}The third step is to render form-item.
How to render the following data into the familiar el-form-item?
{
"type": "input",
"label": "姓名",
"disable": false,
"readonly": false,
"value": "",
"placeholder": "请输入姓名",
"rules": [],
"key": "name",
"subtype": "text"
}The first one, using vue’s built-in component component, may be written like this:
<el-form-item>
<component :is="`el-${item.type}`" />
</el-form-item>The second one, use v-if to judge one by one:
<el-form-item> <el-input v-if="item.type === 'input'" /> <span v-else>未知控件类型</span> </el-form-item>
Consider Since the processing logic of each form control is very different, the author adopted the second method.
According to this idea, we encapsulate a dynamic-form-item , receive an item, and render an el-form-item:
<template>
<el-form-item :rules="item.Rules" :label="item.label" :prop="item.key">
<el-input
v-if="item.type==='input'"
v-bind="$attrs" v-on="$listeners"
:type="item.subtype"
:placeholder="item.placeholder"
:disabled="item.disable"
:readonly="item.readonly"
:autosize="item.autosize"></el-input>
<el-select
v-else-if="item.type==='select'"
v-bind="$attrs" v-on="$listeners"
:multiple="item.multiple"
:disabled="item.disabled"
:multiple-limit="item.multipleLimit">
<el-option
v-for="o in item.options"
:key="o.value"
:label="o.label"
:value="o.value"
:disabled="o.disabled">
</el-option>
</el-select>
<!--突然有点想念JSX-->
...
<span v-else>未知控件类型</span>
</el-form-item>
</template>
<script>
export default {
props: {
item: {
type: Object,
required: true
}
}
}
</script>tips: Use v-bind="$attrs" v-on="$listeners" You can easily forward the v-model directive of the parent component. For details, see vue high-order components.
Finally, we can loop out a complete form:
<dynamic-form-item v-for="item in formConfig.formItemList" :key="item.key" v-if="value[item.key]!==undefined" :item="item" :value="value[item.key]" @input="handleInput($event, item.key)" />
Cannot be used herev-model="value[item.key]" , above As mentioned, props cannot be modified directly within the component, so we will forward it here.
methods: {
handleInput(val, key) {
// 这里element-ui没有上报event,直接就是value了
this.$emit('input', { ...this.value, [key]: val })
},
setDefaultValue() {...}
},Full code address: src/components/dynamic-form/form.vue
##Extended functions
1. Number display unit, limit the number of decimal places
element-ui does not have this function, but I think it is quite common, so I used el-input to manually encapsulate it An input-number: 
<!--普通使用--> <input-number v-model="someNumber" :min="1" :max="99" :decimal1="2" append="元"></input-number> <!--在dynamic-form-item中的应用--> <input-number v-else-if="item.type==='number'" v-bind="$attrs" v-on="$listeners" :min="item.min" :max="item.max" :decimal1="item.decimal1" :append="item.append" :prepend="item.prepend" :disabled="item.disabled"></input-number>Full code:
src/components/dynamic-form/input-number.vue
2. Asynchronous verification
Thanks to async-validator, we can easily customize verification rules. 
{
"type": "input",
...
"rules":[
{
"sql": "SELECT {key} FROM balabala",
"message": "xx已被占用",
"trigger": "blur"
}
]
}In the dynamic-form-item component, traverse item.rules and convert sql verification into Custom validator function:
<template>
<el-form-item :rules="Rules" >
...
</el-form-item>
</template>
<script>
import request from '@/utils/request'
export default {
props: {
item: {...}
},
computed: {
Rules() {
const rules = this.item.rules
if (rules === undefined) return undefined
const R = []
rules.forEach(rule => {
if (rule.sql) {
const validator = (rule2, value, callback) => {
// 根据项目自行修改
request('/api/validate', 'POST', {
key: rule2.field,
value,
sql: rule.sql.replace(/{key}/ig, rule2.field)
})
.then(res => {
callback(!res || undefined)
})
.catch(err => {
this.$message.error(err.message)
callback(false)
})
}
R.push({ validator, message: rule.message, trigger: 'blur' })
} else {
R.push(rule)
}
})
return R
}
},
}
</script>3. Province and city quick configurationThanks to the author of element-china-area-data. In configuration:{
"type": "cascader",
...
"areaShortcut": "provinceAndCityData"
}In dynamic-form-item component:<template> <el-form-item> ... <el-cascader :options="item.options || require('element-china-area-data')[item.areaShortcut]" ></el-cascader> </el-form-item> </template>4. Loading options from remote Including but not limited to radio , checkbox, cascader, selectIn the configuration:
{
"type": "checkbox",
...
"optionsUrl": "/api/some/options"
}In the dynamic-form-item component:<template>
<el-form-item>
...
<el-select>
<el-option
v-for="o in item.options || ajaxOptions"
></el-option>
</el-select>
</el-form-item>
</template>
<script>
import request from '@/utils/request'
export default {
props: {
item: {...}
},
computed: {...},
data() {
return {
ajaxOptions: []
}
},
created() {
const { optionsUrl, key, type } = this.item
if (optionsUrl) {
// 根据项目自行修改
request(`${optionsUrl}?key=${key}`, 'GET')
.then(res => {
this.ajaxOptions = res
})
.catch(err => { this.$message.error(err.message) })
}
}
}
</script>The above is what I compiled for everyone, I hope it will be used in the future Helpful to everyone. Related articles:
nodejs example of method to connect to mongodb database
Select selector multi-selection verification method in iview
Using Axios Element to implement global request loading method
The above is the detailed content of Vue+ElementUI method to realize dynamic rendering and visual configuration of forms. For more information, please follow other related articles on the PHP Chinese website!
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment





