單個(gè)組件動(dòng)態(tài)重新加載,指的是讓某個(gè)已經(jīng)渲染的組件,自動(dòng)銷毀然后開(kāi)始一個(gè)新的生命周期。
組件動(dòng)態(tài)重載
大部分情況下,一個(gè)需求會(huì)很多種實(shí)現(xiàn)方法,而接下來(lái)要說(shuō)明的方法,也是眾多解決方法之一。
1. 業(yè)務(wù)場(chǎng)景
到目前為止,遇到過(guò)兩個(gè)需要實(shí)現(xiàn)這種功能的需求:
1. 后臺(tái)管理系統(tǒng)中,對(duì)頁(yè)面的功能區(qū)域(導(dǎo)航欄、側(cè)邊欄之外的區(qū)域)進(jìn)行局部刷新
簡(jiǎn)單一點(diǎn)的功能頁(yè)面,或許只需要重新加載接口,觸發(fā)一下數(shù)據(jù)更新就夠了,但是某些復(fù)雜的頁(yè)面通過(guò)更新數(shù)據(jù)來(lái)重載狀態(tài),是遠(yuǎn)不如重新渲染組件來(lái)的方便的。
2. 讓一個(gè)彈出式的Canvas畫(huà)布,在依賴的圖片源改變時(shí)重置,圖片未改變時(shí)保持不變。
首先這個(gè)Canvas組件是通過(guò)v-if來(lái)實(shí)現(xiàn)彈出和關(guān)閉的,圖片源不變的情況下,關(guān)閉再?gòu)棾鼋M件是沒(méi)有變化的,圖片源改變的情況下,彈出的組件是初始狀態(tài)。
2. 代碼
通過(guò)外部傳入的值進(jìn)行刷新,指定的props改變時(shí)重載:
<script>
// 假設(shè) AiPlusComponent 是你要使用的 ai-plus 組件
import AiCanvasPlus from '../canvas/plus.vue';
/* 組件 */
let component = null;
let name = null;
export default {
name: 'keep',
props: {
name: {
type: String,
required: true
}
},
render(h) {
/* 不加載緩存 */
if (this.name !== name && component) {
if (component.componentInstance) {
component.componentInstance.$destroy();
}
component = null;
}
/* 保存name */
name = this.name;
if (!component) {
component = h(AiCanvasPlus, {
key: this.name
});
component.data.keepAlive = true
return component;
} else {
return component;
}
}
};
</script>
子組件內(nèi)部觸發(fā),觸發(fā)自定義事件時(shí)自動(dòng)重載:
<script>
// 假設(shè) AiPlusComponent 是你要使用的 ai-plus 組件
import AiCanvasPlus from '../canvas/plus.vue';
/* 組件 */
let component = null;
let name = null;
export default {
name: 'keep',
data() {
return {
name: 'ai'
}
},
render(h) {
/* 不加載緩存 */
if (this.name !== name && component) {
if (component.componentInstance) {
component.componentInstance.$destroy();
}
component = null;
}
/* 保存name */
name = this.name;
if (!component) {
component = h(AiCanvasPlus, {
key: this.name,
onReload(name) {
this.name = name;
}
});
component.data.keepAlive = true
return component;
} else {
return component;
}
}
};
</script>