微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

点击时渲染组件

如何解决点击时渲染组件

我有一个名为 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 不会

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。