Vue.js 提供了一个特殊的元素 <component> 用来动态地挂载不同的组件,使用 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>
动态地改变 currentView 的值就可以动态挂载了.也可以直接绑定在组件对象上:
<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>