Vue2-动态组件案例

2023-12-17 11:39:42

1.component介绍

说明:

  • Type: string | ComponentDefinition | ComponentConstructor

  • Explanation:

    • String: 如果你传递一个字符串给 is,它会被视为组件的名称,用于动态地渲染不同类型的组件。这是一个在运行时动态切换组件类型的常见用例。
    • ComponentDefinition: 你也可以传递组件定义对象,这是一个包含组件选项的对象。
    • ComponentConstructor: 可以传递组件的构造函数。

2.is写法

2.1?is

说明:加载单个组件直接可以不加:

<component is="DynamicMorning"></component>

组件?

<script>
export default {
  name: "morning"
}
</script>

<template>
<div>我是早上组件</div>
</template>

<style scoped>

</style>

2.2?:is?

说明:动态加载组件写法

    <template v-for="item in DynamicComponent">
      <component :is="item.type"></component>
    </template>

2.3源码

<script>
import Dynamic from "@/components/Dynamic/index.vue";
import DynamicMorning  from "@/views/Dynamic/morning.vue";
import DynamicAfternoon from "@/views/Dynamic/afternoon.vue";
import DynamicEvening from "@/views/Dynamic/evening.vue";
export default {
  name: "index",
  components: {
    Dynamic,
    DynamicMorning,
    DynamicAfternoon,
    DynamicEvening
  },
  data() {
    return {
      // 组件数组
      componentArr: [
        {
          id: 1,
          type: 'Morning'
        }, {
          id: 2,
          type: 'Afternoon'
        }, {
          id: 3,
          type: 'Evening'
        }
      ]
    }
  },
  computed:{
    // map遍历同时生成组件名字(类型是个数组)
    DynamicComponent(){
      return  this.componentArr.map(item=>{
        return {
          ...item,
          type:'Dynamic'+item.type
        }
      })

    }
  }
}
</script>

<template>
  <div>
    <h1>我是动态组件父组件</h1>
    <template v-for="item in DynamicComponent">
      <component :is="item.type"></component>
    </template>
  </div>
</template>

<style scoped>

</style>

?

3.源码

<script>
import Dynamic from "@/components/Dynamic/index.vue";
import DynamicMorning from "@/views/Dynamic/morning.vue";
import DynamicAfternoon from "@/views/Dynamic/afternoon.vue";
import DynamicEvening from "@/views/Dynamic/evening.vue";

export default {
  name: "index",
  components: {
    Dynamic,
    DynamicMorning,
    DynamicAfternoon,
    DynamicEvening
  },
  data() {
    return {
      // 组件数组
      componentArr: [
        {
          id: 1,
          type: 'Morning'
        }, {
          id: 2,
          type: 'Afternoon'
        }, {
          id: 3,
          type: 'Evening'
        }
      ]
    }
  },
  computed: {
    // map遍历同时生成组件名字(类型是个数组)
    DynamicComponent() {
      return this.componentArr.map(item => {
        return {
          ...item,
          type: 'Dynamic' + item.type
        }
      })

    }
  }
}
</script>

<template>
  <div>
    <h1>我是动态组件父组件</h1>
    <template v-for="item in DynamicComponent">
      <component :is="item.type"></component>
    </template>
    <!--    <component is="DynamicMorning"></component>-->
  </div>
</template>

<style scoped>

</style>

文章来源:https://blog.csdn.net/m0_62785037/article/details/135041720
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。