VFormRender为VForm的表单渲染器组件,用于将表单JSON对象渲染为Vue组件。
1. 引入并全局注册VFormRender组件
重要提示:如果你在项目中已按照上一节文档注册了VFormDesigner组件,则不再需要注册VFormRender组件。仅当在项目中独立使用VFormRender组件(即项目中不含表单设计器)时才需要注册。
修改vue项目的main.js,如下所示(包含注释的6行代码):
import Vue from 'vue'import App from './App.vue'import axios from 'axios' //如果需要axios,请引入import ElementUI from 'element-ui' //引入element-ui库import VFormRender from 'vform-builds/dist/VFormRender.umd.min.js' //引入VFormRender组件import 'element-ui/lib/theme-chalk/index.css' //引入element-ui样式import 'vform-builds/dist/VFormRender.css' //引入VFormRender样式Vue.config.productionTip = falseVue.use(ElementUI) //全局注册element-uiVue.use(VFormRender) //全局注册VFormRender等组件/* 注意:如果你的项目中有使用axios,请用下面一行代码将全局axios复位为你的axios!! */window.axios = axiosnew Vue({render: h => h(App),}).$mount('#app')
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>export default {data() {return {/* 注意:formJson是指表单设计器导出的json,此处演示的formJson只是一个空白表单json!! */formJson: {"widgetList":[],"formConfig":{"labelWidth":80,"labelPosition":"left","size":"","labelAlign":"label-left-align","cssCode":"","customClass":"","functions":"","layoutType":"PC","onFormCreated":"","onFormMounted":"","onFormDataChange":""}},formData: {},optionData: {}}},methods: {submitForm() {this.$refs.vFormRef.getFormData().then(formData => {// Form Validation OKalert( JSON.stringify(formData) )}).catch(error => {// Form Validation failedthis.$message.error(error)})}}}</script>
3. 添加Vue项目静态资源文件
为加速页面首次加载速度,富文本组件(Vue2Editor)采用了懒加载方式,即表单中包含富文本组件时由浏览器动态加载所需js文件,该文件为”node_modules\vform-builds\dist\VFormRender.umd.min.1.js”。
在开发阶段,需要将该文件复制到Vue项目的静态资源目录(通常为public目录),复制后路径为:
项目根目录\public\js\VFormRender.umd.min.1.js
