單個組件動態(tài)重新加載,指的是讓某個已經(jīng)渲染的組件,自動銷毀然后開始一個新的生命周期。
組件動態(tài)重載
大部分情況下,一個需求會很多種實(shí)現(xiàn)方法,而接下來要說明的方法,也是眾多解決方法之一。
1. 業(yè)務(wù)場景
到目前為止,遇到過兩個需要實(shí)現(xiàn)這種功能的需求:
1. 后臺管理系統(tǒng)中,對頁面的功能區(qū)域(導(dǎo)航欄、側(cè)邊欄之外的區(qū)域)進(jìn)行局部刷新
簡單一點(diǎn)的功能頁面,或許只需要重新加載接口,觸發(fā)一下數(shù)據(jù)更新就夠了,但是某些復(fù)雜的頁面通過更新數(shù)據(jù)來重載狀態(tài),是遠(yuǎn)不如重新渲染組件來的方便的。
2. 讓一個彈出式的Canvas畫布,在依賴的圖片源改變時重置,圖片未改變時保持不變。
首先這個Canvas組件是通過v-if來實(shí)現(xiàn)彈出和關(guān)閉的,圖片源不變的情況下,關(guān)閉再彈出組件是沒有變化的,圖片源改變的情況下,彈出的組件是初始狀態(tài)。
2. 代碼
通過外部傳入的值進(jìn)行刷新,指定的props改變時重載:
<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ā)自定義事件時自動重載:
<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>