# 动态组件

让多个组件使用同一个挂载点(component),并动态切换,这就是动态组件。

通过使用保留的 <component> 元素,动态地绑定到它的 is 特性,可以实现动态组件

<div id="example">
	<button @click="change">切换页面</button>
	<component :is="currentView"></component>
</div>
<script>
	var home = { template: "<div>我是主页</div>" };
	var post = { template: "<div>我是提交页</div>" };
	var archive = { template: "<div>我是存档页</div>" };
	new Vue({
		el: "#example",
		components: {
			home,
			post,
			archive,
		},
		data: {
			index: 0,
			arr: ["home", "post", "archive"],
		},
		computed: {
			currentView() {
				return this.arr[this.index];
			},
		},
		methods: {
			change() {
				this.index = ++this.index % 3;
			},
		},
	});
</script>

动态组件缓存 <keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 <transition> 相似,<keep-alive>是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在父组件链中

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<title>Document</title>
		<script src="05-vue/lib/vue.js"></script>
		<style>
			.on {
				color: red;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<ul>
				<li v-for="item in list" :key="item.name" @click="currentComponents = item.components">
					{{ item.name }}
				</li>
			</ul>
			<div class="box">
				<keep-alive>
					<component :is="currentComponents"></component>
				</keep-alive>
			</div>
		</div>
		<script>
			var vm = new Vue({
				el: "#app",
				data() {
					return {
						isActive: true,
						red: "red",
						currentComponents: "com1",
						list: [
							{
								name: "组件1",
								components: "com1",
							},
							{
								name: "组件2",
								components: "com2",
							},
							{
								name: "组件3",
								components: "com3",
							},
						],
					};
				},
				components: {
					com1: {
						data() {
							return {
								info: "组件1",
							};
						},
						template: "<p>{{ info }}</p>",
					},
					com2: {
						data() {
							return {
								info: "组件2",
							};
						},
						template: "<p>{{ info }}</p>",
					},
					com3: {
						data() {
							return {
								info: "子组件内容",
								nowIndex: 100,
							};
						},
						template: `
              <ul>
                <li @click="nowIndex = 1" :class="{on : nowIndex == 1}">张三</li>  
                <li @click="nowIndex = 2" :class="{on : nowIndex == 2}">李四</li>  
                <li @click="nowIndex = 3" :class="{on : nowIndex == 3}">王五</li>  
              </ul>
            `,
					},
				},
			});
		</script>
	</body>
</html>
上次更新: 11/26/2019, 10:43:50 AM