<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
,看下面代碼。
Vue.component('child-one', {
template: `<div v-once>child-one</div>`,
})
Vue.component('child-two', {
template: `<div v-once>child-two</div>`,
})
加上v-once
指令之後,有什麼好處呢?當chlid-one
組件第一次被渲染時,因爲組件上面有一個v-once
指令,所以它直接就放到內存裏了,當切換的時候child-two
組件第一次被渲染時,它也會被放到內存裏,再次點擊切換時,這時並不需要再重新創建一個child-one
組件了,而是從內存裏直接拿出以前的child-one
組件,它的性能會更高一些。
所以在 Vue 當中,通過v-once
指令,可以提高一些靜態內容的展示效率