vue单页应用的内存泄露定位和修复问题小结

2020-06-12 21:15:44易采站长站整理


<template>
<div id="home">
这里是首页
</div>
</template>

<script>
export default {
mounted () {
window.test = { // 此处在全局window对象中引用了本页面的dom对象
name: 'home',
node: document.getElementById('home')
}
}
}
</script>


按下Heap snapshots键,搜索Detached,发现没有脱离文档树的dom元素,属于正常现象

改变路由跳转到other页面,按下Heap snapshots键,搜索Detached,发现有两处dom元素游离于当前页面之外,很明显是window对象引用了home页面中的div,即使此时home页面已经销毁,home中的dom元素却还驻留在内存中无法释放。

解决方案就是在页面卸载的时候顺便处理掉该引用。


<template>
<div id="home">
这里是首页
</div>
</template>

<script>
export default {
mounted () {
window.test = { // 此处在全局window对象中引用了本页面的dom对象
name: 'home',
node: document.getElementById('home')
}
},
destroyed () {
window.test = null // 页面卸载的时候解除引用
}
}
</script>

2.除了直接引用,window的原生方法也会起到引用dom元素使其无法释放的效果。


<template>
<div id="home">这里是首页</div>
</template>

<script>
export default {
mounted () {
window.addEventListener('resize', this.func) // window对象引用了home页面的方法
},
methods: {
func () {
console.log('这是home页面的函数')
}
}
}
</script>

 解决方法一样,也是在页面销毁的时候,顺便解除引用,释放内存


mounted () {
window.addEventListener('resize', this.func)
},
beforeDestroy () {
window.removeEventListener('resize', this.func)
}

3.一些全局的方法使用不当也会造成内存无法释放,在页面卸载的时候也可以考虑解除引用