vue动态组件 component

该文章演示了在Vue.js中如何利用<component>元素的is属性动态切换多个组件,并结合keep-alive实现组件缓存。当用户点击<ul>中的列表项时,index会改变,从而切换渲染不同的组件(如时间选择器、下拉框、姓名输入框)。同时,文章提到了keep-alive的activated和deactivated生命周期钩子,分别在组件激活和被替换时触发,用于管理组件的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在一个挂载点使用多个组件,并进行动态切换,使用<component>元素的 is 的特性

<!-- 动态组件由 vm 实例的 componentName 控制 -->
<component :is="componentName"></component>

根据绑定的is的值决定哪个组件被渲染

<template>
  <div class="hello"> 
    <ul>
      <li 
      v-for="(item,index) in tab" 
      :key="index" 
      style="cursor:pointer" 
      @click="changeView(index)">
      {{item}}
      </li>
      <keep-alive>
		<component :is="currentView"></component>
	  </keep-alive>
    </ul>
  </div>
</template>

<script> 
export default {  
  data() {
    return {
      index: 0,
      arr: ["inputDatePicker", "inputSelect", "inputName"], // 组件已在main.js全局引入
      tab: ["时间选择器组件", "下拉框组件", "顾客姓名输入框组件"],
    };
  },
  computed: {
    currentView() {
      return this.arr[this.index];
    }
  },
  methods: {
    changeView(index) {
      this.index = index;
    }
  },

  // keep-alive 两个生命周期
  activated() {
     console.log("inputDatePicker 时间选择器组件被添加");// 被缓存的组件激活时触发
   },
   deactivated() {
     console.log("inputDatePicker 时间选择器组件被移除"); // 被切换到其他组件时触发
   }

};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值