業務場景: 在某個業務場景中, 我們需要在數據庫配置ts文件路徑,和需要調用的函數名稱, 前端需要再指定的場景下,觸發對應的函數, 并執行處理邏輯,返回結果.
實現: 這是一個數據庫配置生成的動態表單 + 動態校驗的例子, 需要引用動態的函數校驗
- 任意一個js文件,
common1.ts
const funcation1 = ({value, formParam}) =>{console.log('我進來了1',value,formParam);// todo: 特殊邏輯處理return '我出去了';
}
const funcation2 = ({value, formParam}) =>{console.log('我進來了2',value,formParam);// todo: 特殊邏輯處理return '我出去了';
}export {
funcation1,
funcation2
}
- 在需要調用的位置, 加入如下代碼.
main.vue
<script>/**動態調用函數*/const loadAndCallFunction = async(modelPath, funcionName, param) =>{try{// 動態導入模塊const module = await import(`./${modelPath}`);// 檢查模塊是否包含指定的函數if(typeof module[funcionName] === 'function') {// 調用函數并返回結果return module[funcionName](param);}throw new Error(`Function ${funcionName} not found In module ${modelPath}`)}catch(error) {throw error}}const rules = reactive<any>({});// 根據后端配置,動態渲染表單rulesconst initRule = (formItems) =>{formItems.map((item)=>{rules[item.field] = item.rule !== undefined ? item.rule : [{required:false}];if(item.validator !== undefined) {const validator = {validator: async (value, cb)=>{//const result:any = await loadAndCallFunction(item.path, item.function, {value, formValue})const result:any = await loadAndCallFunction('validator/common/common1', 'function1', {value, formValue});if(result === '' || result === undefined){cb();} else {cb(result);}}} }})}
</script>
最終的運行效果: