vue动态组件 component

在一个挂载点使用多个组件,并进行动态切换,使用<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>

猜你喜欢

转载自blog.csdn.net/future_1_/article/details/129013226