Vue向数组推送新建配方对象后清空输入触发搜索计算属性报错问题
报错根因
- 存在对象引用污染问题:
AgregarReceta方法中直接将this.new_receta的对象引用推入lista_recetas数组,没有做独立拷贝。后续代码执行this.new_receta.nombre = null时,数组中刚存入的新配方对象的nombre字段会同步被修改为null。 - 计算属性无空值防护:
lista_recetas_filtrada的过滤逻辑直接对value.nombre调用toLowerCase()方法,遇到值为null的条目就会直接抛出Cannot read property 'toLowerCase' of null错误。 - 表单重置逻辑不规范:重置输入框内容时将字段赋值为
null,而非空字符串,本身也不符合表单控件的值类型预期。
修复方案
- 修改
AgregarReceta方法,存入数组前对表单数据做独立拷贝,存入完成后重置整个表单为初始空状态,避免引用联动污染历史数据:AgregarReceta: function () { // 拷贝当前表单的所有内容,切断和原表单对象的引用关联 const recetaParaGuardar = { ...this.new_receta, ingredientes: [...this.new_receta.ingredientes] } this.lista_recetas.push(recetaParaGuardar); // 重置整个表单为初始空结构,所有字段使用空字符串,不使用null this.new_receta = { id: "", nombre: "", descripcion: "", chef: "", ingredientes: [] } this.nuevo_ingrediente = '' console.log("Agregada") } - 修改
AgregarIngrediente方法的重置逻辑,不要将原料输入框的值设为null,统一重置为空字符串:AgregarIngrediente: function () { const new_date = new Date(); const ingrediente = { "id": 'i1000' + new_date.getTime(), "nombre": this.nuevo_ingrediente, } this.new_receta.ingredientes.push(ingrediente); this.nuevo_ingrediente = '' // 替换原来的null赋值 } - 给计算属性的过滤逻辑增加空值兜底,避免后续再有空值输入时触发同类报错:
lista_recetas_filtrada: function () { const self = this return this.lista_recetas.filter( function (value) { // 空值统一转成空字符串再做匹配,从根源避免null/undefined触发方法调用报错 const targetNombre = value.nombre || '' const searchKey = self.search || '' return targetNombre.toLowerCase().includes(searchKey.toLowerCase()) } ) }
内容的提问来源于stack exchange,提问作者Ivan Parra
相关产品推荐
相关产品推荐

