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

Vue.js中如何将父组件计算的数组长度传递给progressBar子组件使用

实现方案

步骤1:修改progressBar子组件,声明接收参数

在子组件的script中添加props字段,声明要接收的arrayLength参数,修改后的完整子组件代码如下:

<template>
    <div id="main-progress">
      <!-- 可直接在模板中使用arrayLength,比如展示总卡片数 -->
      <div>总任务数:{{ arrayLength }}</div>
      <div class="progress-wrapper">
        <b-progress
          v-model="value"
          max="100"
        />
      </div>
    </div>
</template>

<script>
import { BProgress } from 'bootstrap-vue'

export default ({
    components: {
        BProgress,
    },
    // 新增props声明
    props: {
      arrayLength: {
        type: Number,
        default: 0 // 未传值时的默认值
      }
    },
    data(){
        return {
            value: 0,
        }
    },
    methods: {
      // 子组件方法中可通过this.arrayLength直接访问传入的值
      demoMethod() {
        console.log('父组件传入的数组长度:', this.arrayLength)
      }
    }
})
</script>

步骤2:修改trailCard父组件,绑定传值

找到父组件template中引用progressBar子组件的位置,通过动态绑定属性的方式传入arrayLength变量,示例如下:

<template>
  <div class="trail-card-wrapper">
    <!-- 其他父组件逻辑 -->
    <!-- 绑定arrayLength到子组件,注意驼峰props在模板中要转成短横线分隔写法 -->
    <progress-bar :array-length="arrayLength" />
  </div>
</template>

父组件原本的mounted中计算arrayLength的逻辑不需要修改,计算完成后会自动同步到子组件。

可选:监听数值变化做响应式处理

如果后续trail_card数组会动态增删导致arrayLength变化,子组件需要同步触发逻辑的话,可以在子组件中添加watch监听:

watch: {
  arrayLength(newVal) {
    // 数值变化后触发的逻辑,比如重新计算进度条值
    console.log('数组长度更新为:', newVal)
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:57:04