- 使用
<component>
元素动态挂载不同的组件,使用is
特性来选择要挂载的组件 - 先在实例中注册三个组件,然后在实例的
data
选项中给currentview
设置一个默认显示的组件,接着在methods
中创建方法并使用v-on
监听DOM事件,动态改变currentview
对应的组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<style>
#app{
border: 1px dotted #5c6b77;
width: 600px;
height: 400px;
}
.container-btns{
margin-top: 2px;
width: 600px;
height: 42px;
border-bottom: 1px #5c6b77 dotted;
}
.container-btn{
width: 120px;
height: 40px;
line-height: 10px;
border: 1px solid #f7f7f7;
}
.cpn-change{
width: 600px;
height: 356px;
}
</style>
<div id="app">
<div class="container">
<div class="container-btns">
<button class="container-btn" @click="handleClick('A')">切换到A</button>
<button class="container-btn" @click="handleClick('B')">切换到B</button>
<button class="container-btn" @click="handleClick('C')">切换到C</button>
</div>
<div class="cpn-change">
<component :is="currentview"></component>
</div>
</div>
</div>
<template id="com-a">
<div>
<span>Hello! I am coma</span>
</div>
</template>
<template id="com-b">
<div>
<span>Hello! I am comb</span>
</div>
</template>
<template id="com-c">
<div>
<span>Hello! I am comc</span>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
let comA = {
template: "#com-a"
}
let comB = {
template: "#com-b"
}
let comC = {
template: "#com-c"
}
let app = new Vue({
el: "#app",
data: {
currentview: comA
},
components: {
comA,
comB,
comC
},
methods: {
handleClick(component) {
this.currentview = 'com' + component
}
}
})
</script>
</body>
</html>