首页 > 解决方案 > vue 在点击时渲染组件

问题描述

我有一个名为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) {
  
  }
}

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

标签: vue.jsvue-componentvue-render-function

解决方案


您可以将 修改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>


推荐阅读