前面的话
在我们平时使用vue中的模板的时候,许多时候都是直接定义成一个固定的模板,但是,vue中提供了一个动态模板,可以在任意模板中切换,就是用vue中用:is来挂载不同的组件。
像下图这样,点击不同按钮,切换不同的组件:
只需在< component></ component>中绑定一个特殊的属性: is,就可以实现了。
代码实现
<!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="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<component :is="currentView"></component>
<button @click="handleChangeView('A')">A</button>
<button @click="handleChangeView('B')">B</button>
<button @click="handleChangeView('C')">C</button>
</div>
</body>
</html>
<script>
var app = new Vue({
el: '#app',
components:{
comA: {
template: `
<div>组件A</div>
`
},
comB: {
template: `
<div>组件B</div>
`
},
comC: {
template: `
<div>组件C</div>
`
}
},
data: {
currentView: 'comA'
},
methods: {
handleChangeView(component) {
this.currentView = "com" + component
}
}
})
</script>