1.当不同的组件之间进行切换的时候,使用动态组件会非常有用
2.动态组件使用一个特殊的属性 is 来实现组件间的切换,is属性的内容值可以为一个已经注册的组件的名字,或者是一个组件的选项对象,此时该组件会根据is属性指定的内容对组件进行渲染显示
<component :is="ComponentName"></component>
3.解析DOM模板的时候需要注意,有些HTML元素,如ul, ol, table, select等,对于哪些元素可以出现在其内部是有严格要求的,而有些元素,如li,tr,option只能出现在某些特定元素的内部,这将会导致使用这些约束元素时出现问题,此时可以使用is这个特殊的属性动态对内容进行指定来解决
// 出错情况: 这里自定义组件child-component组件会被视为无效的内容被提升到外部,导致渲染的最终结果出错
<table>
<child-component></child-component>
</table>
// 对于以上的这种问题可以修改为以下所示即可解决
<table>
<tr :is="child-component"></tr>
</table>
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态组件</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.11.7/dayjs.min.js"></script>
</head>
<body>
<div id="app">
<div id="content">
<component :is='list[id-1]'></component>
</div>
<button @click="chooseContent(1)">首页</button>
<button @click="chooseContent(2)">列表</button>
<button @click="chooseContent(3)">个人</button>
<button @click="chooseContent(4)">新闻</button>
</div>
</body>
<script>
let com1 = Vue.component('index-com', {
template: '<h1>首页内容---</h1>'
})
let com2 = Vue.component('list-com', {
template: '<h1>列表内容---</h1>'
})
let com3 = Vue.component('news-com', {
template: '<h1>个人内容---</h1>'
})
let com4 = Vue.component('me-com', {
template: '<h1>新闻内容---</h1>'
})
let app = new Vue({
el: "#app",
data(){
return{
id: 1,
list:['index-com','list-com','news-com','me-com']
}
},
methods: {
chooseContent: function (id) {
this.id = id;
}
}
})
</script>
</html>