我正在使用表单窗口小部件,其中表单由从我的api检索的模式生成。我正在使用的表单库具有内置验证器(vue-form-generator),它们通过库直接引用。例如:
"schema": {
"fields": [{
"type": "input",
"inputType": "email",
"label": "E-mail",
"model": "email",
"placeholder": "Email",
"validator": "VueFormGenerator.validators.email",
"required": true
},{
"type": "submit"
}]
}
这是我的代码:
<template>
<div id="app" v-if="loaded">
<vue-form-generator :schema="schema" :model="model" :options="formOptions"></vue-form-generator>
</div>
</template>
<script>
/* eslint no-eval: 0 */
import Vue from 'vue'
import VueFormGenerator from 'vue-form-generator/dist/vfg-core.js'
import 'vue-form-generator/dist/vfg-core.css'
Vue.use(VueFormGenerator)
export default {
name: 'app',
data: function () {
return {
loaded: false,
model: null,
schema: null,
formOptions: null
}
},
created: function () {
return fetch('http://localhost:3000/forms')
.then((response) => response.json())
.then((json) => {
// evaluate the validator
json.schema.fields.map((field) => {
if (field.validator) {
field.validator = eval(field.validator)
}
return field
})
// assign the schema and model
this.model = json.model
this.schema = json.schema
this.formOptions = json.formOptions
// indicate that the schema has bee loaded
this.loaded = true
})
.catch((ex) => {
console.log('parsing failed', ex)
})
}
}
</script>
我的想法是我可以使用eval()
来评估验证器的名称并将其转换为实际函数。但是,我收到以下错误:
parsing failed ReferenceError: VueFormGenerator is not defined
at eval (eval at <anonymous> (eval at <anonymous> (http://localhost:8080/app.js:797:1)), <anonymous>:1:1)
at eval (eval at <anonymous> (http://localhost:8080/app.js:797:1), <anonymous>:35:29)
at Array.map (native)
at eval (eval at <anonymous> (http://localhost:8080/app.js:797:1), <anonymous>:33:26)
at <anonymous>
有没有办法做到这一点,还是在本地创建转换以将验证者名称映射到实际函数的更好选择?
谢谢!
答案 0 :(得分:1)
您可以尝试使用reduce:
json.schema.fields.map((field) => {
if (field.validator) {
// get every key after VueFormGenerator
const keys = field.validator.split('.').slice(1)
// use reduce to get back the deepest prop
field.validator = keys.reduce((obj, key) => obj[key], VueFormGenerator)
}
return field
})