1.component介绍
说明:
-
Type:
string | ComponentDefinition | ComponentConstructor
-
Explanation:
- String: 如果你传递一个字符串给
is
,它会被视为组件的名称,用于动态地渲染不同类型的组件。这是一个在运行时动态切换组件类型的常见用例。 - ComponentDefinition: 你也可以传递组件定义对象,这是一个包含组件选项的对象。
- ComponentConstructor: 可以传递组件的构造函数。
- String: 如果你传递一个字符串给
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>