動態組件
如果我們打算在一個地方根據不同的狀態引用不同的組件的話,比如tab頁,那麼Vue給我們提供動態組件。
基本使用
Parent.vue
<template>
<div>
<el-button-group>
<el-button v-for='(btn, index) in btnGroup'
:key="index" :class="{active:btn.disabled}"
@click='change(index)'>{{btn.name}}
</el-button>
</el-button-group>
<div>
<component :is='currentCom'></component>
</div>
</div>
</template>
<script>
import Childs1 from './Childs1'
import Childs2 from './Childs2'
import Childs3 from './Childs3'
import Childs4 from './Childs4'
export default {
name:'Parent',
components:{
Childs1,
Childs2,
Childs3,
Childs4
},
data() {
return {
btnGroup: [
{name: 'Childs1', disabled: true},
{name: 'Childs2', disabled: false},
{name: 'Childs3', disabled: false},
{name: 'Childs4', disabled: false},
],
currentCom:'Childs1'
}
},
methods: {
change(index){
let pre = Number(this.currentCom[this.currentCom.length -1]);
this.btnGroup[pre -1].disabled = false;
this.btnGroup[index].disabled = true;
this.currentCom = 'Childs' + (index + 1);
}
}
}
</script>
<style scoped>
.active{
background-color: red;
}
</style>
運行結果如下圖:
當我們點擊不同的按鈕時,下面會切換不同的組件。實現動態組件的加載。is
的值可以是一個已經註冊的組件的名字或者一個組件的選對象。當我們點擊按鈕時,這個按鈕的 disabled
爲 true
然後我們將給這個按鈕一個active
的css類,同時改變 currentCom
的值
keep-alive
:動態組件的緩存
如果我們需要頻繁的切換頁面,每次都是在組件的創建和銷燬的狀態間切換,這無疑增大了性能的開銷。那麼我們要怎麼優化呢? Vue
提供了動態組件的 緩存
。keep-alive
會在切換組件的時候緩存當前組件的狀態,等到再次進入這個組件,不需要重新創建組件,只需要從前面的緩存中讀取並渲染。
Parent.vue(其餘地方代碼和上面一樣)
<template>
<div>
<el-button-group class='btn-group'>
<el-button v-for='(btn, index) in btnGroup'
:key="index" :class="{active:btn.disabled}"
@click='change(index)'>
{{btn.name}}
</el-button>
</el-button-group>
<div style='padding-top:100px;'>
<keep-alive>
<component :is='currentCom'></component>
</keep-alive>
</div>
</div>
</template>
<style scoped>
.btn-group{
position:fixed;
}
.active{
background-color: red;
}
</style>
Childs1.vue
<template>
<div>
{{title}}
<button @click='change'>點我+1</button>
</div>
</template>
<script>
export default {
name:'Childs1',
data(){
return{
title: 1
}
},
methods:{
change(){
this.title += 1;
}
},
mounted(){
console.log('child1 mounted');
}
}
</script>
Childs2.vue
<template>
<div>
Childs2
</div>
</template>
<script>
export default {
name:'Childs2',
mounted(){
console.log('child2 mounted');
}
}
</script>
運行結果如下圖:
'
對比:如果我們將<keep-alive></keep-alive>去掉,運行結果如下圖:
前一組圖片在切換組件的時候,title
從1加到3,然後等下次再切換回來的時候,title
還是停留在3,從控制檯可以看出,Childs1.vue
這個組件的mounted
的鉤子函數只有一次。後一組圖片,title
一開始加到3,下一次進入這個組件的時候title
又從1開始,控制檯圖片也顯示這個組件經歷個了多次鉤子函數,說明組件是銷燬重建的。
tips
:因爲緩存的組件只需要建立一次,所以如果我們要在每次進入組件的鉤子函數裏面做相應的操作的時候,會出現問題,所以請明確我們使用的場景,避免出現bug
異步組件
異步組件
存在的意義在於加載一個體量很大的頁面時,如果我們不設置加載的優先級
的話,那麼可能頁面在加載視頻等信息的時候會非常佔用時間,然後主要信息就會阻塞
在後面在加載。這對用戶來說無疑不是一個很差的體驗。但是如果我們設置加載的順序,那麼我們可以優先那些最重要的信息優先顯示
,優化了整個項目。一般來說我們是將加載組件和 路由
(vue-router
)配合在一起使用,所以這裏我就不細講了,具體學習可以參考官網來進行學習。