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: '首页内容---
'
})
let com2 = Vue.component('list-com', {
template: '列表内容---
'
})
let com3 = Vue.component('news-com', {
template: '个人内容---
'
})
let com4 = Vue.component('me-com', {
template: '新闻内容---
'
})
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>

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54