Laravel给Vue复用的新增编辑表单传值时空属性读取报错如何解决
问题修复方案
错误原因说明
- 新增路由加载报错:新增场景下
person为null,你使用this.person != ''作为判断条件,JS中null == ''的结果为false,判断会进入真值分支,尝试读取null.name就抛出了属性读取错误。 - 编辑场景更新按钮报错:Vue模板中不需要加
this.前缀访问实例属性,错误的this.person写法在事件绑定场景下会出现指向异常,导致读取不到person属性。
具体修复步骤
1. 优化prop定义,增加类型校验和默认值
把props的数组写法改成对象写法,明确类型和默认值,避免基础类型错误:
export default { name: 'PeopleForm', // 替换原来的 props: ['person'] props: { person: { type: Object, default: null } }, // 剩余代码不变 }
2. 修正data中form的初始化逻辑
把所有this.person != ''的判断替换成this.person(对象为真值,null为假值,直接判断即可):
data: function () { return { form: { name: this.person ? this.person.name : '', lastname: this.person ? this.person.lastname : '', age: this.person ? this.person.age : '', dni: this.person ? this.person.dni : '', email: this.person ? this.person.email : '', // 新增编辑场景车辆id的回填逻辑 id_car: this.person ? this.person.id_car : 1, }, errors: null, options: [ 'foo', 'bar', 'baz' ] } },
3. 修正模板中的所有判断逻辑
删除模板里所有this.前缀,同时替换判断条件:
<!-- 标题部分 --> <h1 class="block w-full text-center text-gray-800 text-2xl font-bold mb-6"> {{person ? 'Update' : 'Create'}} </h1> <!-- 按钮部分 --> <button @click="person ? update(person.id) : store()" class="w-full bg-blue-400 hover:bg-blue-600 transition duration-500 ease-in-out text-white p-3 rounded" type="submit"> {{person ? 'Update' : 'Create'}} </button>
4. 修复store方法中的表单重置错误
原代码中this.form.splice(0)是错误写法,form是对象不是数组,没有splice方法,需要手动重置属性:
store: function () { axios.post("/people", this.form) .then(() => { this.$swal({ title: "People created", icon: 'success', toast: true, showConfirmButton: false, position: 'top-end', timerProgressBar: true, timer: 5000 }) // 正确的表单重置逻辑 this.form = { name: '', lastname: '', age: '', dni: '', email: '', id_car: 1, } }).catch((e) => { if (e.response.data.message == "Error") { this.$swal({ title: "Email or DNI already exist", icon: 'error', toast: true, showConfirmButton: false, position: 'top-end', timerProgressBar: true, timer: 5000 }) } this.errors = e.response.data.errors; }); },
内容的提问来源于stack exchange,提问作者El Hombre Sin Nombre
相关产品推荐
相关产品推荐

