1、beforeDestroy
beforeDestroy周期一般是在組件銷(xiāo)毀時(shí)調(diào)用,比如使用v-if進(jìn)行組件的顯示隱藏,或者頁(yè)面跳轉(zhuǎn)時(shí)就會(huì)調(diào)用到這個(gè)周期。
堆內(nèi)存使用后一定要注意釋放,否則gc總不回收就會(huì)導(dǎo)致內(nèi)存泄漏。
比如對(duì)dom的引用、事件Listener、總線eventBus等,一定要在beforeDestroy里釋放解綁。
export default {
name:'test',
data(){
return {
width: window.innerWidth,
height: window.innerHeight
}
},
mounted() {
this.resizeFunc = () => {
this.width = window.innerWidth;
this.height = window.innerHeight;
};
window.addEventListener('resize', this.resizeFunc);
},
beforeDestroy(){
window.removeEventListener('resize',this.resizeFunc);
this.resizeFunc = null;
}
}
2、利用weakmap和weakset
當(dāng)vue中有Dom引用時(shí),需要注意內(nèi)存釋放問(wèn)題。weakset 和 weakmap對(duì)值的引用都是不計(jì)入垃圾回收機(jī)制的。也就是說(shuō),如果其他對(duì)象都不再引用該對(duì)象,那么垃圾回收機(jī)制會(huì)自動(dòng)回收該對(duì)象所占用的內(nèi)存。
export default {
name: 'test',
data() {
return {
wp: new WeakMap()
}
},
mounted() {
let ele = document.getElementById('con');
let handleFunc = () => {
console.log(ele.innerHTML);//閉包,對(duì)ele有引用,不容易釋放
}
this.wp.set(ele, handleFunc);//建立節(jié)點(diǎn)和事件的關(guān)系
ele.addEventListener('click', this.wp.get(ele), false);
},
beforeDestroy() {
this.ele.removeEventListener('click',this.wp.get(this.ele));//清理掛載事件
}
}
3、路由守衛(wèi)beforeRouteLeave
如果是對(duì)router進(jìn)行了keep-alive,那進(jìn)行頁(yè)面跳轉(zhuǎn)時(shí)就不會(huì)觸發(fā)beforeDestroy,也就是對(duì)組件進(jìn)行了緩存,不會(huì)銷(xiāo)毀組件,這時(shí)我們可以用路由守衛(wèi)來(lái)確保釋放資源。
beforeRouteLeave (to, from, next) {
// 導(dǎo)航離開(kāi)該組件的對(duì)應(yīng)路由時(shí)調(diào)用
this.$destroy();//手動(dòng)調(diào)用beforeDestroy釋放資源,或者單獨(dú)定義哪些資源需要釋放
next(); //允許跳轉(zhuǎn)頁(yè)面
},
4、移除watch
如果是手動(dòng)調(diào)用監(jiān)聽(tīng)watch的,也需要釋放一下資源。
export default {
data() {
return {
test: 'jack'
}
},
watch: {
test(newVal, oldVal) {
console.log(newVal);
}
},
methods:{
startWatch(){
this.unwatch = this.$watch('test',(newval,oldval)=>{
//this.$watch會(huì)返回一個(gè)取消監(jiān)聽(tīng)的函數(shù)句柄
console.log('watch>>>',newval);
});
}
},
beforeDestroy() {
// 移除監(jiān)聽(tīng)
this.unwatch && this.unwatch();//執(zhí)行銷(xiāo)毀監(jiān)聽(tīng)
}
}