Vue動態掛載不同的元件
阿新 • • 發佈:2018-12-15
<!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>Vue動態掛載不同的元件</title>
</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>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
var Home={
template:'<p>Welcome home</p>'
}
var app = new Vue({
el: '#app',
components: {
// 元件A
comA: {
template: '<div>元件A</div>',
},
// 元件B
comB: {
template: '<div>元件B</div>'
},
// 元件C
comC: {
template: '<div>元件C</div>'
}
},
data: {
currentView: 'Home' //試試 'comA' 'comB'
},
methods: {
// 點選事件傳參切換不同的元件
handleChangeView(component) {
console.log(component)
this.currentView = 'com' + component;
}
}
})
</script>
</body>
</html>