动态组件用于频繁切换组件
(1)刚开始
<body>
<div id="root">
<child-one v-if="type === 'child-one'"></child-one>
<child-two v-if="type === 'child-two'"></child-two>
<button @click="change">change</button>
</div>
<script>
//创建子组件
Vue.component('child-one', {
template: `<div>
child-one
</div>`
})
Vue.component('child-two', {
template: `<div>
child-two
</div>`
})
//创建vue实例对象
var vm = new Vue({
el: '#root',
data: {
type: 'child-one'
},
methods: {
change() {
this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
}
}
})
</script>
</body>
改进后
<div id="root">
<component :is="type"></component>
<button @click="change">change</button>
</div>
//创建子组件
Vue.component('child-one', {
template: `<div v-once>
child-one
</div>`
})
Vue.component('child-two', {
template: `<div v-once>
child-two
</div>`
})