Vue2中使用vue-form-generator组件报错:模板或渲染函数未定义
解决Vue2中vue-form-generator组件挂载失败的问题
看到你遇到的这个报错:
[Vue warn]: Failed to mount component: template or render function not defined. found in vue-form-generator

问题出在你的组件导入、注册方式以及语法细节上,我来一步步帮你修正:
1. 修复导入语句的语法错误
你的代码里导入时误用了转义引号\",这会导致JavaScript解析异常,把它改成正常的引号即可:
// 错误写法 import VueFormGenerator from \"vue-form-generator\"; // 正确写法 import VueFormGenerator from "vue-form-generator";
2. 修正组件注册逻辑
当你调用Vue.use(VueFormGenerator)时,已经全局注册了vue-form-generator组件,此时不需要再在当前组件的components选项里重复声明它——这种重复注册会导致你把插件对象当成组件注册,从而引发挂载失败的错误。
修改后的完整script代码如下:
<script> import Vue from 'vue' import VueFormGenerator from "vue-form-generator"; Vue.use(VueFormGenerator); // 全局注册组件,无需再局部声明 export default { // 移除 components: { VueFormGenerator }, 这一行 data: () => ({ model: { id: 1, name: "John Doe", password: "J0hnD03!x4", skills: ["Javascript", "VueJS"], email: "john.doe@gmail.com", status: true }, schema: { fields: [{ type: "input", inputType: "text", label: "ID (disabled text field)", model: "id", readonly: true, disabled: true },{ type: "input", inputType: "text", label: "Name", model: "name", placeholder: "Your name", featured: true, required: true },{ type: "input", inputType: "password", label: "Password", model: "password", min: 6, required: true, hint: "Minimum 6 characters", validator: VueFormGenerator.validators.string },{ type: "select", label: "Skills", model: "skills", values: ["Javascript", "VueJS", "CSS3", "HTML5"] },{ type: "input", inputType: "email", label: "E-mail", model: "email", placeholder: "User's e-mail address" },{ type: "checkbox", label: "Status", model: "status", default: true }] }, formOptions: { validateAfterLoad: true, validateAfterChanged: true } }) } </script>
可选:局部注册组件(如果你不想全局注册)
如果你更倾向于局部注册而非全局注册组件,可以这样调整:
import { VueFormGenerator } from "vue-form-generator"; // 导入具体组件 export default { components: { VueFormGenerator }, // 局部注册组件 // ... 其他数据和配置代码保持不变 }
这种方式下,你不需要调用Vue.use(VueFormGenerator)。
做完这些修改后,组件应该就能正常挂载,字段动态加载的功能也能正常运行了。
内容的提问来源于stack exchange,提问作者Ashwini
相关产品推荐
相关产品推荐

