Vue@2.6.10+Rails6环境下表单组件化后页面消失无报错如何修复
问题根因
- 核心问题是父组件模板误用了原生
<form>标签渲染自定义组件:你注册的自定义组件名为Form,但模板中直接写<form>会被Vue识别为HTML原生表单标签,而非你引入的Form组件,自然不会渲染任何自定义内容,也不会报错。 - 自定义组件的props定义格式不符合Vue2规范:对象类型的props默认值需要用工厂函数返回,你当前的props写法不符合语法要求。
- 自定义事件命名冲突:用原生
click作为自定义事件名容易和标签原生点击事件混淆,建议更换语义化的自定义事件名。 - 直接修改props不符合单向数据流规范:Vue2不推荐子组件直接修改props值,虽然对象是引用类型修改不会直接报错,但不符合官方最佳实践。
修复代码
1. 修复后 New.vue
<template> <!-- 用注册的组件名<Form> 替代原生<form>,自定义事件改为submit-form避免冲突 --> <Form :latest_information.sync="latest_information" @submit-form="createLatestInformation"></Form> </template> <script> import Form from './Form.vue'; export default { components:{ Form }, data() { return { latest_information: { title: '', detail: '', }, } }, methods: { createLatestInformation() { this.$loading.load(this.$auth.api.post('admin/latest_informations/', { latest_information: this.latest_information }) .then(response => { this.$router.push({name: 'AdminLatestInformationIndex'}) })) } }, } </script>
2. 修复后 Form.vue
<template> <main> <form> <section> <div> <div> <fieldset> <div class="form-row"> <div class="form-group col-3"> <label>タイトル</label> <input :value="latest_information.title" @input="$emit('update:latest_information', {...latest_information, title: $event.target.value})" type="text"> </div> <div class="form-group col-3"> <label>詳細</label> <input :value="latest_information.detail" @input="$emit('update:latest_information', {...latest_information, detail: $event.target.value})" type="text"> </div> </div> </fieldset> </div> </div> </section> <div class="btn-container d-flex justify-content-center"> <button class="button-square btn-send" type="button" @click="$emit('submit-form')">保存する</button> </div> </form> </main> </template> <script> export default { props: { latest_information: { // 指定props类型为对象 type: Object, // 对象类型默认值用工厂函数返回 default: () => ({ title: '', detail: '' }), required: true }, } } </script> <style> </style>
补充说明
如果是简单业务场景不想用.sync修饰符,也可以利用对象的引用特性直接在子组件v-model绑定props的属性,不会影响基础功能,仅不符合单向数据流的最佳实践。
内容的提问来源于stack exchange,提问作者katahik
相关产品推荐
相关产品推荐

