Vue3动态表单实现

实现方法:通过<component />标签动实现动态表单渲染

component标签:

在vue中 component 标签用于动态组件标签的渲染。它允许在同一个挂载点上条件渲染不同的组件,通过is属性可以渲染指定的属性

在上面的例子中,通过调用函数applyCom实现在页面上渲染Com2组件

动态表单渲染(Vue3 + ElementPlus)

* 文件列表

* widgets/index.js

在index.js中导入所有的表单元素组件

复制代码
export { default as WidgetInput } from "./input.vue";

export { default as WidgetTextarea } from "./textarea.vue";

export { default as WidgetSelect } from "./select.vue";

export { default as WidgetRadio } from "./radio.vue";

export { default as WidgetUpdate } from "./upload.vue";

* widgets/input.vue

复制代码
<template>
  <div>
    <el-input v-model="model" style="width: 240px" v-bind="$attrs"  />
  </div>
</template>

<script setup>
import { ref } from "vue";

const props = defineProps({
    modelValue:{
        type:Number
    }
})

const emits = defineEmits(['update:modelValue']);

const model = useVModel(props,'modelValue',emits);
</script>
  1. 通过v-model确保数据的单向流

  2. $attrs: 当想要将所有未声明的属性都是用在组件上可以使用,那么这里就会将component组件上的绑定的v-bind的数据全部应用到input这个组件之上。

* form.vue

复制代码
<template>
  <ElForm ref="formRef" labelPosition="top" @submit.prevent>
    <ElFormItem v-for="(item, index) in arr" :key="index">
      <component
        :is="getWidgetByName(item.name)"
        v-model="item.value"
        v-bind="item.apply"
      />
    </ElFormItem>
  </ElForm>
</template>
<script setup>
import * as widgets from "./widgets";

let arr = [
  {
    name: "WidgetInput",
    value: 1,
    apply: {
      placeholder: "请输入数字",
    },
  },
  {
    name: "WidgetInput",
    value: 2,
    apply: {
      placeholder: "请输入数字",
    },
  },

  {
    name: "WidgetSelect",
    value: 3,
    apply: {
      placeholder: "请输入数字",
    },
  },
];
const getWidgetByName = (name) => {
  return widgets[name];
};
</script>
相关推荐
Predestination王瀞潞10 分钟前
5.4.3 通信->WWW万维网内容访问标准(W3C):WWW(World Wide Web) 协议架构(分层)
前端·网络·网络协议·架构·www
爱学习的程序媛20 分钟前
【Web前端】优化Core Web Vitals提升用户体验
前端·ui·web·ux·用户体验
zabr21 分钟前
花了 100+ 篇笔记,我整理出 了一套 AI Agent 工程完全指南
前端·后端·agent
软弹33 分钟前
深入理解 React Ref 机制:useRef 与 forwardRef 的协作原理
前端·javascript·react.js
YaHuiLiang37 分钟前
Ai Coding浪潮下的前端:“AI在左,裁员在右”
前端
雪碧聊技术1 小时前
前端vue代码架子搭建
前端·javascript·vue.js·前端项目代码框架搭建
爱学习的程序媛1 小时前
【Web前端】前端用户体验优化全攻略
前端·ui·交互·web·ux·用户体验
han_1 小时前
JavaScript设计模式(二):策略模式实现与应用
前端·javascript·设计模式
x***r1511 小时前
Notepad++ 8.6 安装教程:详细步骤+自定义安装路径(附注意事项)
linux·前端·javascript
Hilaku1 小时前
为什么很多工作 5 年的前端,身价反而卡住了?🤷‍♂️
前端·javascript·面试