VFormRender为VForm 3的表单渲染器组件,用于将表单JSON对象渲染为Vue组件。

1. 引入并全局注册VFormRender组件

重要提示:如果你在项目中已按照上一节文档注册了VFormDesigner组件,则不再需要注册VFormRender组件。仅当在项目中独立使用VFormRender组件(即项目中不含表单设计器)时才需要注册。

修改vue项目的main.js,如下所示(包含注释的6行代码):

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import axios from 'axios' //如果需要axios,请引入
  4. import ElementPlus from 'element-plus' //引入element-plus库
  5. import VFormRender from 'vform3-builds/dist/render.umd.js' //引入VFormRender组件
  6. import 'element-plus/dist/index.css' //引入element-plus样式
  7. import 'vform3-builds/dist/render.style.css' //引入VFormRender样式
  8. const app = createApp(App)
  9. app.use(ElementPlus) //全局注册element-plus
  10. app.use(VFormRender) //全局注册VFormRender等组件
  11. /* 注意:如果你的项目中有使用axios,请用下面一行代码将全局axios复位为你的axios!! */
  12. window.axios = axios
  13. app.mount('#app')

醒目提示:你如果的Vue 3项目使用TS(TypeScript),则应该增加如下配置内容: 在项目src目录下新建types目录,新增一个index.d.ts,文件内容仅一行:
declare module “vform3-builds”

2. 在Vue模板中使用组件

重要提示:如果表单json对象是通过后台接口异步获取到的,用form-json属性传值则会导致表单校验提示异常,需要调用setFormJson(xxx)方法,具体参见此处文档——《渲染表单》

  1. <template>
  2. <div>
  3. <v-form-render :form-json="formJson" :form-data="formData" :option-data="optionData" ref="vFormRef">
  4. </v-form-render>
  5. <el-button type="primary" @click="submitForm">Submit</el-button>
  6. </div>
  7. </template>
  8. <script setup>
  9. import { ref, reactive } from 'vue'
  10. import { ElMessage } from 'element-plus'
  11. /* 注意:formJson是指表单设计器导出的json,此处演示的formJson只是一个空白表单json!! */
  12. const formJson = reactive({"widgetList":[],"formConfig":{"modelName":"formData","refName":"vForm","rulesName":"rules","labelWidth":80,"labelPosition":"left","size":"","labelAlign":"label-left-align","cssCode":"","customClass":"","functions":"","layoutType":"PC","jsonVersion":3,"onFormCreated":"","onFormMounted":"","onFormDataChange":"","onFormValidate":""}})
  13. const formData = reactive({})
  14. const optionData = reactive({})
  15. const vFormRef = ref(null)
  16. const submitForm = () => {
  17. vFormRef.value.getFormData().then(formData => {
  18. // Form Validation OK
  19. alert( JSON.stringify(formData) )
  20. }).catch(error => {
  21. // Form Validation failed
  22. ElMessage.error(error)
  23. })
  24. }
  25. </script>