动态组件:不同组件之间进行动态切换。
代码实现如下:
<!DOCTYPE html>
<html>
<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></title>
</head>
<body>
<div id="app">
<!-- <button @click="change('com1')">组件1</button> -->
<!-- <button @click="change('com2')">组件2</button> -->
<button @click="com='com1'">组件1</button>
<button @click="com='com2'">组件2</button>
<component :is="com"></component>
</div>
</body>
</html>
<script src="./js/vue.js"></script>
<script>
Vue.component("com1", {
template: `
<div>
我是组件1
</div>
`
})
Vue.component("com2", {
template: `
<div>
我是组件2
</div>
`
})
new Vue({
el: "#app",
data: {
com: "com2"
},
methods: {
change(str) {
this.com = str;
}
},
})
</script>
运行结果如下所示:
点击不同的按钮,显示的内容也不同。