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

Vue如何实现点击按钮后才渲染对应customer-type组件,降低初始渲染开销

实现方案

你可以通过维护一个已触发渲染的行索引集合,结合v-if条件判断实现按需渲染,具体修改如下:

1. 新增响应式状态存储已渲染行标识

在组件的data选项中新增renderedRows数组,用于记录用户已经点击触发渲染的行索引,初始值为空:

data() {
  return {
    // 其他原有数据
    renderedRows: []
  }
}

2. 给组件添加渲染条件判断

在customer-type组件上添加v-if指令,仅当当前行索引存在于renderedRows中时才渲染组件:

<template v-for="(date, index) in daysOfYear">
  <b-tr :key="date" :id="`row-${getDay(date)}`">
    <!-- 新增v-if判断 -->
    <customer-type 
      v-if="renderedRows.includes(index)"
      :id="`customer-${index}`" 
      @test="setCustomer" 
      v-bind:listTypes="listTypes"  
    />
    <button @click="renderComponent(index)">渲染组件</button>
  </b-tr>
</template>

3. 完善点击触发方法

点击按钮时将当前行索引存入renderedRows数组,触发组件渲染,增加去重逻辑避免重复添加:

methods: {
  renderComponent(index) {
    // 已经添加过的索引不重复处理
    if (!this.renderedRows.includes(index)) {
      this.renderedRows.push(index)
    }
  }
}

可选优化

如果需要支持点击按钮切换显示/隐藏组件,可以把方法改成切换逻辑:

renderComponent(index) {
  const idx = this.renderedRows.indexOf(index)
  if (idx > -1) {
    this.renderedRows.splice(idx, 1)
  } else {
    this.renderedRows.push(index)
  }
}

如果customer-type组件体积较大,还可以配合Vue的异步组件进一步优化加载性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 00:36:04