vue render components on click

4.1k views Asked by At

I have a component called customer-type.

I do have the full year and I do have a lot of components as well. So I want to reduce rendering.

How can I load a component after click 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) {
  
  }
}

I don't want to render the component before I explicitly click on it.

2

There are 2 answers

0
aswin putra On

@Majed is right. Basically, v-if will only render the element in the DOM when the condition is met. Another alternative is v-show basically it works the same way as v-if, the difference is that v-show will always render the element in the DOM and v-if won't

0
Majed Badawi On

You can modify the daysOfYear to be a list of objects, each having a boolean to show/hide its customer-type component using v-if.

Here is a simple demo:

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>