jformer 是一個動態表單呈現組件,只須要傳遞 json 數據就能夠顯示出界面和功能css
element 表單組件外須要套一個 el-form-item 實現前綴顯示和數據驗證,如今基於 jformer 擴展一個渲染處理 provider 簡化這個定義html
<!DOCTYPE html><html lang="en"> <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta http-equiv="X-UA-Compatible" content="ie=edge" /><title>Static Template</title><script src="https://cdn.jsdelivr.net/npm/vue"></script><script src="https://cdn.jsdelivr.net/npm/jformer"></script><script src="https://cdn.jsdelivr.net/npm/element-ui/lib/index.js"></script><script src="./element-ext.js"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-ui/lib/theme-chalk/index.css"/> </head> <body><div id="app"> <j-former v-bind:config="config"></j-former></div><script> new Vue({data() { return {config: {} }; },async mounted() { const response = await fetch("./config.json"); this.config = await response.json(); } }).$mount("#app");</script> </body></html>複製代碼
element-ext.js 實現了一個渲染處理 provider, 將定義組件外套一層 el-form-item,並將組件的 elForm 屬性做爲 el-form-item 的屬性vue
// 實現一個渲染處理 provider 實如今組件上定義 elForm// 就能夠自動在組件外層加上 el-form-itemconst elementFormProps = (field) => { if (!field.elForm) {return; } // 複製組件原始配置 const originField = { ...field }; // 將組件名改爲 el-form-item field.component = "el-form-item"; // 將原組件的複製賦給組件下級實現改變界面結構 field.children = [originField]; // 將 elForm 屬性做爲 el-form-item 的屬性 field.fieldOptions = {props: field.elForm }; // 若是組件關聯了數據屬性則將數據屬性做爲 el-form-item 的數據屬性 if (originField.model) { field.fieldOptions.props.prop = originField.model; } // 刪除 elForm 定義避免下級組件渲染處理時無限循環 delete field.elForm; delete originField.elForm; };// 將定義的 provider 應用於 jformerwindow.jformer.default.use(({ provider }) => { provider(elementFormProps); });複製代碼
{ "fields": [ { "component": "el-form", "fieldOptions": {"ref": "form","props": { "labelWidth": "120px", "model": "$:model" } }, "children": [ { "component": "el-input", "model": "text1", "fieldOptions": { "attrs": { "placeholder": "請輸入" } }, "elForm": {"label": "輸入1","rules": [{ "required": true, "message": "必填項" }] } }, { "component": "el-input", "model": "text2", "fieldOptions": {"attrs": { "placeholder": "輸入 1 多於5個字以後就必填" } }, "elForm": {"label": "輸入2","rules": [ { "required": "$:model.text1.length>5", "message": "必填項" } ] } }, { "component": "div", "elForm": { "label": "" }, "children": [ { "component": "el-button", "text": "提交", "events": [ { "name": "click", "handler": "@:refs.form.validate()" } ], "fieldOptions": { "props": { "type": "primary" } } }, { "component": "el-button", "text": "重置"} ] } ] } ] }複製代碼
示例完整實現:
codesandbox.io/s/jformer-t…git
預覽效果:
d9c7b.csb.app/github