说明:
Type: string | ComponentDefinition | ComponentConstructor
Explanation:
is
,它会被视为组件的名称,用于动态地渲染不同类型的组件。这是一个在运行时动态切换组件类型的常见用例。说明:加载单个组件直接可以不加:
<component is="DynamicMorning"></component>
组件?
<script>
export default {
name: "morning"
}
</script>
<template>
<div>我是早上组件</div>
</template>
<style scoped>
</style>
说明:动态加载组件写法
<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>
?
<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>