VFormRender为VForm 3的表单渲染器组件,用于将表单JSON对象渲染为Vue组件。
1. 引入并全局注册VFormRender组件
重要提示:如果你在项目中已按照上一节文档注册了VFormDesigner组件,则不再需要注册VFormRender组件。仅当在项目中独立使用VFormRender组件(即项目中不含表单设计器)时才需要注册。
修改vue项目的main.js,如下所示(包含注释的6行代码):
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios' //如果需要axios,请引入
import ElementPlus from 'element-plus' //引入element-plus库
import VFormRender from 'vform3-builds/dist/render.umd.js' //引入VFormRender组件
import 'element-plus/dist/index.css' //引入element-plus样式
import 'vform3-builds/dist/render.style.css' //引入VFormRender样式
const app = createApp(App)
app.use(ElementPlus) //全局注册element-plus
app.use(VFormRender) //全局注册VFormRender等组件
/* 注意:如果你的项目中有使用axios,请用下面一行代码将全局axios复位为你的axios!! */
window.axios = axios
app.mount('#app')
醒目提示:你如果的Vue 3项目使用TS(TypeScript),则应该增加如下配置内容: 在项目src目录下新建types目录,新增一个index.d.ts,文件内容仅一行:
declare module “vform3-builds”
2. 在Vue模板中使用组件
重要提示:如果表单json对象是通过后台接口异步获取到的,用form-json属性传值则会导致表单校验提示异常,需要调用setFormJson(xxx)方法,具体参见此处文档——《渲染表单》。
<template>
<div>
<v-form-render :form-json="formJson" :form-data="formData" :option-data="optionData" ref="vFormRef">
</v-form-render>
<el-button type="primary" @click="submitForm">Submit</el-button>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
/* 注意:formJson是指表单设计器导出的json,此处演示的formJson只是一个空白表单json!! */
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":""}})
const formData = reactive({})
const optionData = reactive({})
const vFormRef = ref(null)
const submitForm = () => {
vFormRef.value.getFormData().then(formData => {
// Form Validation OK
alert( JSON.stringify(formData) )
}).catch(error => {
// Form Validation failed
ElMessage.error(error)
})
}
</script>