Vue3中为延迟挂载的指定div配置Lenis Scroll并全局访问实例
解决Vue3中延迟挂载div的Lenis Scroll全局访问问题
方法一:将Lenis实例挂载到window对象
在目标组件的mounted钩子中创建Lenis实例,同时赋值给window对象,实现全局环境直接调用:
<script setup> import Lenis from '@studio-freight/lenis' import { onMounted } from 'vue' onMounted(() => { const lenis = new Lenis({ content: document.getElementById('lenis-target') }) // 挂载到window,全局可访问 window.lenis = lenis function raf(time) { lenis.raf(time) requestAnimationFrame(raf) } requestAnimationFrame(raf) }) // 示例:在事件中调用停止方法 const stopScroll = () => { window.lenis?.stop() } </script>
后续在项目任意位置(控制台、其他组件事件等),直接用window.lenis.stop()即可调用实例方法。
方法二:使用Vue全局属性
在项目入口文件注册全局属性,再在组件中初始化实例并赋值:
- 入口文件配置:
// main.js import { createApp } from 'vue' import App from './App.vue' const app = createApp(App) // 注册全局属性用于存储Lenis实例 app.config.globalProperties.$lenis = null app.mount('#app')
- 组件中初始化:
<script setup> import Lenis from '@studio-freight/lenis' import { onMounted, getCurrentInstance } from 'vue' const appInstance = getCurrentInstance() onMounted(() => { const lenis = new Lenis({ content: document.getElementById('lenis-target') }) // 赋值给全局属性 appInstance.appContext.config.globalProperties.$lenis = lenis function raf(time) { lenis.raf(time) requestAnimationFrame(raf) } requestAnimationFrame(raf) }) // 调用示例 const stopScroll = () => { appInstance.appContext.config.globalProperties.$lenis?.stop() } </script>
其他组件可通过getCurrentInstance获取全局属性来调用Lenis方法。
方法三:用状态管理工具(Pinia)统一管理实例
适合大型项目,统一管控Lenis实例的生命周期:
- 创建Pinia Store:
// stores/lenisStore.js import { defineStore } from 'pinia' import Lenis from '@studio-freight/lenis' export const useLenisStore = defineStore('lenis', { state: () => ({ instance: null }), actions: { init(targetId) { const target = document.getElementById(targetId) if (!target) return this.instance = new Lenis({ content: target }) const raf = (time) => { this.instance.raf(time) requestAnimationFrame(raf) } requestAnimationFrame(raf) }, stop() { this.instance?.stop() }, start() { this.instance?.start() }, destroy() { this.instance?.destroy() this.instance = null } } })
- 在组件中使用:
<script setup> import { useLenisStore } from '@/stores/lenisStore' import { onMounted, onUnmounted } from 'vue' const lenisStore = useLenisStore() onMounted(() => { lenisStore.init('lenis-target') }) // 路由切换/组件卸载时销毁实例,避免内存泄漏 onUnmounted(() => { lenisStore.destroy() }) // 调用停止方法示例 const stopScroll = () => { lenisStore.stop() } </script>
这种方式可在任意组件中通过Store访问Lenis实例,还能统一处理实例的创建与销毁逻辑。
注意事项
- 若目标元素为异步渲染(如接口请求后生成),需在元素渲染完成后再初始化Lenis,可配合
nextTick或监听元素存在状态。 - 组件卸载/路由切换时,记得调用
lenis.destroy()销毁实例,防止内存泄漏。
内容的提问来源于stack exchange,提问作者AnnaGino
相关产品推荐
相关产品推荐

