fix(lenis): 改进平滑滚动插件的清理逻辑
添加销毁状态检查和浏览器卸载事件处理,确保在热更新和页面卸载时正确清理资源
This commit is contained in:
@@ -5,7 +5,7 @@ import { ScrollTrigger } from 'gsap/ScrollTrigger'
|
||||
|
||||
gsap.registerPlugin(ScrollTrigger)
|
||||
|
||||
export default defineNuxtPlugin((nuxtApp) => {
|
||||
export default defineNuxtPlugin(() => {
|
||||
// 用 Lenis 平滑浏览器原始 wheel 输入,避免鼠标滚轮一格跳太远。
|
||||
const lenis = new Lenis({
|
||||
lerp: 0.075,
|
||||
@@ -21,12 +21,22 @@ export default defineNuxtPlugin((nuxtApp) => {
|
||||
gsap.ticker.add(updateLenis)
|
||||
gsap.ticker.lagSmoothing(0)
|
||||
|
||||
// Nuxt 卸载时清掉 ticker 和事件,避免热更新或页面销毁后重复驱动滚动。
|
||||
nuxtApp.hook('app:beforeUnmount', () => {
|
||||
let isDestroyed = false
|
||||
const cleanupLenis = () => {
|
||||
if (isDestroyed) {
|
||||
return
|
||||
}
|
||||
|
||||
isDestroyed = true
|
||||
lenis.off('scroll', ScrollTrigger.update)
|
||||
gsap.ticker.remove(updateLenis)
|
||||
window.removeEventListener('beforeunload', cleanupLenis)
|
||||
lenis.destroy()
|
||||
})
|
||||
}
|
||||
|
||||
// Nuxt 没有类型化的 app:beforeUnmount;这里用浏览器卸载和 Vite 热更新做清理。
|
||||
window.addEventListener('beforeunload', cleanupLenis)
|
||||
import.meta.hot?.dispose(cleanupLenis)
|
||||
|
||||
return {
|
||||
provide: {
|
||||
|
||||
Reference in New Issue
Block a user