Vue.js 提供了一個特殊的元素 <component> 用來動態(tài)地掛載不同的組件,使用 js 特性來選擇要掛載的組件.示例代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>示例</title>
</head>
<body>
<div id="app">
<component :is="currentView"></component>
<button @click="handleChangView('A')">切換到A</button>
<button @click="handleChangView('B')">切換到B</button>
<button @click="handleChangView('C')">切換到C</button>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
var app = new Vue({
el: '#app',
component: {
comA: {
template: '<div>組件A</div>'
},
comB: {
template: '<div>組件B</div>'
},
comC: {
template: '<div>組件C</div>'
}
},
data: {
currentView: 'comA'
},
methods: {
handleChangView: function (component) {
this.currentView = 'com' + component;
}
}
})
</script>
</body>
</html>
動態(tài)地改變 currentView 的值就可以動態(tài)掛載了.也可以直接綁定在組件對象上:
<div id="app">
<component :is="currentView"></component>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
var Home = {
template: '<p>Welcome home!</p>'
};
var app = new Vue({
el: '#app',
data: {
currentView: Home
}
})
</script>