点击时渲染组件

问题描述

我有一个名为 customer-type 的组件。

我确实有一整年,我也有很多组件。所以我想减少渲染。

如何在点击 renderComponent 后加载组件?

<template v-for="(date,index) in daysOfYear">
  <b-tr :key="date" :id="`row-${getDay(date)}`">
    <customer-type :id="`customer-${index}`" @test="setCustomer" v-bind:listTypes="listTypes"  />
    <button @click="renderComponent(index)"> </button>
  </b-tr>
</template>
methods: {
  renderComponent(index) {
  
  }
}

我不想在明确点击组件之前渲染它。

解决方法

您可以将 daysOfYear 修改为一个对象列表,每个对象都有一个布尔值来使用 customer-type 显示/隐藏其 v-if 组件。

这是一个简单的演示:

const customertype = Vue.component('customertype',{ template: '#customertype',props: ['id'] });

new Vue({
  el:"#app",components: { customertype },data: () => ({ 
    daysOfYear: ['01-01-2021','01-02-2021','01-03-2021']
  }),created() {
    this.daysOfYear = this.daysOfYear.map(date => ({ date,showCustomerType:false }));
  },methods: {
    renderComponent(index) {
      this.daysOfYear[index].showCustomerType = true;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template id="customertype"><p>{{id}}</p></template>

<div id="app">
  <div v-for="({ date,showCustomerType },index) in daysOfYear" :key="index">
    <button @click="renderComponent(index)">Show</button>
    <customertype 
      v-if="showCustomerType" 
      :id="`customer-${index}`"
    />
  </div>
</div>

,

@Majed 是对的。基本上,v-if 只会在满足条件时呈现 DOM 中的元素。另一种选择是 v-show 基本上它的工作方式与 v-if 相同,区别在于 v-show 将始终呈现 DOM 中的元素而 v-if 不会