Vue.js 2父组件向子组件传字符串prop,子组件接收为undefined问题求助
问题原因及修复方案
核心错误1:Prop命名规则不匹配
Vue 2 的HTML模板中属性名不区分大小写,驼峰格式的Prop在父组件传递时必须转为短横线分隔命名:
- 子组件定义的Prop是驼峰格式
sensorType,父组件模板中传递时不能写:sensorType,要改为:sensor-type,否则Vue会将属性识别为全小写的sensortype,和子组件声明的Prop无法匹配,自然返回undefined。
父组件模板修改后代码:
<ls-sensor v-if="lsSensor" :sensor-type="checkedSensor" />
错误2:事件触发与变量更新的时序问题
Vue 2 中v-model的赋值更新时机晚于change事件触发时机,你在change回调中直接切换子组件显示状态时,checkedSensor还没被赋予最新的选中值,子组件渲染时拿到的还是旧值。
修复方案:用$nextTick包裹组件显隐逻辑,等变量赋值完成后再渲染子组件,修改后的showDeviceComponent方法:
showDeviceComponent(e) { this.$nextTick(() => { if (e == "ls") { this.lsSensor = true; this.crSensor = false; this.dgSensor = true; console.log("file input component", this.checkedSensor) } else if (e == "dg") { this.dgSensor = true; this.lsSensor = false; this.crSensor = false; } else { this.crSensor = true; this.dgSensor = false; this.lsSensor = false; } }) }
逻辑优化建议
你当前用3个复选框绑定同一个字符串变量的用法不符合复选框的原生逻辑:
- 如果需求是三个选项互斥(同一时间只能选一个),建议换成
v-radio配合v-radio-group实现,逻辑更清晰 - 如果需求支持多选,需要把
checkedSensor的初始值改为数组类型[],不要用字符串
内容的提问来源于stack exchange,提问作者swapmeet_Lou
相关产品推荐
相关产品推荐

