Vue 动态组件与 v-once 指令的实现

2020-06-14 05:58:20易采站长站整理

本文介绍了Vue 动态组件与 v-once 指令的实现,分享给大家,具体如下:


<div id="root">
<child-one></child-one>
<child-two></child-two>
<button>change</button>
</div>
Vue.component('child-one', {
template: `<div>child-one</div>`,
})
Vue.component('child-two', {
template: `<div>child-two</div>`,
})
let vm = new Vue({
el: '#root'
})

上面代码需实现,当点击按钮时,child-one和child-two实现toggle效果,该怎么实现呢?


<div id="root">
<child-one v-if="type === 'child-one'"></child-one>
<child-two v-if="type === 'child-two'"></child-two>
<button @click="handleBtnClick">change</button>
</div>
Vue.component('child-one', {
template: `<div>child-one</div>`,
})
Vue.component('child-two', {
template: `<div>child-two</div>`,
})
let vm = new Vue({
el: '#root',
data: {
type:'child-one'
},
methods: {
handleBtnClick(){
this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
}
}
})

通过上面handleBtnClick函数的实现,配合v-if指令就能实现toggle效果

动态组件

下面这段代码实现的效果和上面是一样的。


<div id="root">
<component :is="type"></component> //is内容的变化,会自动的加载不同的组件
<button @click="handleBtnClick">change</button>
</div>
Vue.component('child-one', {
template: `<div>child-one</div>`,
})
Vue.component('child-two', {
template: `<div>child-two</div>`,
})
let vm = new Vue({
el: '#root',
data: {
type:'child-one'
},
methods: {
handleBtnClick(){
this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
}
}
})

动态组件的意思是它会根据is里面数据的变化,会自动的加载不同的组件

v-noce指令

每次点击按钮切换的时候,Vue 底层会帮我们干什么呢?Vue 底层会判断这个child-one组件现在不用了,取而代之要用child-two组件,然后它就会把child-one组件销毁掉,在创建一个child-two组件。假设这时child-two组件要隐藏,child-one组件要显示,这个时候要把刚刚创建的child-two销毁掉,在重新创建child-one组件,也就是每一次切换的时候,底层都是要销毁一个组件,在创建一个组件,这种操作会消耗一定的性能。如果我们的组件的内容,每次都是一样的可以在上面加一个v-once,看下面代码。