在Vue项目中使用Three.js出现明显卡顿

现象:单页写的物体自动移动移植到Vue项目中明显卡顿

原因:用浏览器开发者工具中的Performance分析网页性能,发现有一项reactiveGetter耗时占比高,展开其中包含调用Three.js相关函数,结合Vue响应式原理,Vue会对data里面的变量进行变化追踪,占用了资源。

解决方法:将data中的数据写到mounted中或者定义当页局部变量

在Vue项目中退出动画页面还会调用requestAnimationFrame

现象:在Vue项目中某页面Web3D动画渲染器更新用到了requestAnimationFrame,退出页面的时候F12调试发现还在一直打印requestAnimationFrame的回调函数未定义

原因:可能requestAnimationFrame式window下的方法,经过调试页面退出确实调用了beforeDestroy,但是cancelAnimationFrame未进行取消

解决方法:在beforeDestroy钩子函数中对requestAnimationFrame回调进行取消操作
相关代码:

// render
render: function () {
	//_this是在mounted中初始化好的_this = this
	_this.timer = requestAnimationFrame(_this.render); 
}

//cancel
beforeDestroy() {
	cancelAnimationFrame(this.timer);
}
Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐