You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BootstrapVue项目中子组件如何判断父组件传入的props值并实现对应逻辑

解决方案

你遇到的问题核心是两个:props响应式更新没处理、不需要给禁用状态的按钮绑定点击事件,对应修改方案如下:

1. 父组件补充逻辑

在选中内容为空时重置传参,确保子组件能感知状态变化:

methods: {
  inputedValue(input, index) {
    var array = [];
    const item= this.json.find((i) => i.Number === input);
    for (let key in item.ID) {
      array.push(item.ID[key]);
    }
    if(array.length > 0) {
      this.getIndex = index;
      this.getDataArray = array;
      this.getLengthArray = array.length;
    } else {
      // 新增:无选中内容时重置长度
      this.getLengthArray = 0;
      this.getIndex = null;
    }
  }
}

同时确保父组件调用子组件时正确传递props:

<child :get-length-array="getLengthArray" :get-index="getIndex" />

2. 子组件脚本修改

  • 不要把props赋值给data初始化,子组件初始化时父组件可能还没拿到选中值,后续props更新也不会同步到data
  • 新增watch监听父组件传的长度参数,自动触发批量生成输入框的逻辑
props: [
  "getLengthArray",
  "getIndex"
],
data() {
  return {
    inputs: [{}],
    hide: false,
  }
},
watch: {
  // 监听长度参数变化
  getLengthArray(newVal) {
    if (newVal > 0) {
      this.addElementsNotClickable(newVal)
      this.hide = true
    } else {
      this.hide = false
      // 可选:无选中时重置输入框为初始状态
      this.inputs = [{}]
    }
  }
},
methods: {
  addElementsNotClickable(length) {
    // 先清空原有输入框避免重复添加
    this.inputs = [{}]
    for(let i = 1; i < length; i++) {
      this.inputs.push({})
    }
  },
  addElement() {
    this.inputs.push({})   
  },
}

3. 子组件模板修改

禁用状态的按钮不需要绑定任何点击事件,直接加disabled属性实现不可点击效果即可:

<div class="mt-4 mb-5 ml-3 mr-3">
  <b-button v-if="!hide" @click="addElement" variant="block">Add Element</b-button>
  <b-button v-if="hide" disabled variant="block">Not clickable !</b-button>
</div>

内容的提问来源于stack exchange,提问作者user16365685

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 09:36:05