I'm working a form widget where the form is generated by schema that's retrieved from my api. The form library I'm using has built-in validators (vue-form-generator) that are referenced directly via the library. For example:
"schema": {
"fields": [{
"type": "input",
"inputType": "email",
"label": "E-mail",
"model": "email",
"placeholder": "Email",
"validator": "VueFormGenerator.validators.email",
"required": true
},{
"type": "submit"
}]
}
And here's my code:
<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>
My thought was that I could use eval() to evaluate the name of the validator and have it translate to a real function. However, I get the following error:
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>
Is there a way to do this or is it a better option to create a translation locally to map validator names to actual functions?
Thanks!
VueFormGenerator.validators.emailand there's nothing calledVueFormGeneratorin scope. I don't know how to do what you want but that's what's going wrong.