<template>
<div id="app">
<component :is="currentView" v-bind="componentProps"></component>
<button @click="changeView('A')">切换到A</button>
<button @click="changeView('B')">切换到B</button>
<button @click="changeView('C')">切换到C</button>
</div>
</template>
<script>
var app = new Vue({
el: '#app',
data: {
currentView: 'comA',
name:'Lily'
},
methods: {
changeView: function(data){
this.currentView = 'com'+ data //动态地改变currentView的值就可以动态挂载组件了。
}
},
components: {
comA: {
props:{
name:{
type:String,
default:''
}
}
template: '<p>组件A{{name}}</p>'
},
comB: {
template: '<p>组件B</p>'
},
comC: {
template: '<p>组件C</p>'
}
},
componentProps() {
if (this.componentIndex == 'A') {
return {
name: this.name
}
}
return{}
}
});
</script>
https://cn.vuejs.org/v2/guide/components-dynamic-async.html 推荐