vue中的动态组件
- 动态组件是由vue内置标签component上的is属性确定的,is属性的值,就是组件的名字
第二种方法,用v-for,需要注意的是,type的值只是用来做标识的
<div id="app">
<component :is="type"></component>
<!-- <child-one v-if="type === 'child-one'"></child-one>
<child-two v-if="type === 'child-two'"></child-two> -->
<button @click="toggle">click me</button>
</div>
<script>
Vue.component( 'child-one', {
template: `<div>child-one</div>`,
})
Vue.component('child-two', {
template: `<div>child-two</div>`
})
var vm = new Vue({
el: '#app',
data: {
type: 'child-one'
},
methods: {
toggle(){
this.type = (this.type === 'child-one' ? this.type = 'child-two' : this.type = 'child-one')
}
}
})
</script>
同时要注意:局域组件好像不可以实现动态组件,刚用局域组件写的时候,总是报错
上述的切换存在一定的问题:组件一和组件二来回切换的过程,底层原理是:销毁一个创建一个,然后点击切换的过程中其实就是销毁和创建的切换,这样非常浪费性能
(1)知识点:v-once,作用:带有v-once指令的标签,会缓存,这样下次调用该标签的时候,直接去缓存中取
<div id="app">
<!-- <component :is="type"></component> -->
<child-one v-if="type === 'child-one'"></child-one>
<child-two v-if="type === 'child-two'"></child-two>
<button @click="toggle">click me</button>
</div>
<script>
Vue.component( 'child-one', {
template: `<div v-once>child-one</div>`,
})
Vue.component('child-two', {
template: `<div v-once>child-two</div>`
})
var vm = new Vue({
el: '#app',
data: {
type: 'child-one'
},
methods: {
toggle(){
this.type = (this.type === 'child-one' ? this.type = 'child-two' : this.type = 'child-one')
}
}
})
</script>
(2)可以通过
<keep-alive>
<component :is="type"></component>
</keep-alive>
还没有评论,来说两句吧...