Vue3如何在Router的index.js中通过Provide/Inject获取Lenis实例?
解决Vue Router中调用Lenis实例的问题
为什么inject在这里无效?
inject是Vue组件实例的专属API,仅能在组件上下文(比如setup函数、组件钩子)中使用。而scrollBehavior是路由实例的配置方法,不属于任何组件实例,自然无法通过inject获取到你在main.js中provide的Lenis实例。
推荐解决方案:模块导出共享实例
最规范的方式是将Lenis实例抽离为独立模块,让组件和路由都导入同一个实例,避免依赖组件上下文。
- 创建独立的Lenis实例文件
在src/utils/lenis.js中创建并导出实例:
import Lenis from '@studio-freight/lenis' // 初始化Lenis实例 export const lenis = new Lenis({ duration: 1.2, easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)), // 其他你的配置项 }) // 启动RAF更新,保证平滑滚动生效 function raf(time) { lenis.raf(time) requestAnimationFrame(raf) } requestAnimationFrame(raf)
- 在main.js中provide实例
保持组件可以通过inject获取实例:
import { createApp } from 'vue' import App from './App.vue' import { lenis } from './utils/lenis' const app = createApp(App) app.provide('lenis', lenis) // 组件依然可以通过inject('lenis')获取 app.mount('#app')
- 在router中直接导入使用
在router/index.js里导入实例,直接调用scrollTo:
import { createRouter, createWebHistory } from 'vue-router' import { lenis } from '../utils/lenis' import routes from './routes' const router = createRouter({ history: createWebHistory(), routes, scrollBehavior(to, from, savedPosition) { if (savedPosition) { // 恢复保存的滚动位置 lenis.scrollTo(savedPosition.top, { immediate: true }) return savedPosition } if (to.hash) { // 滚动到锚点 lenis.scrollTo(to.hash, { duration: 1000, easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)) }) return { el: to.hash } } // 默认滚动到顶部 lenis.scrollTo(0, { duration: 800 }) return { top: 0 } } }) export default router
备选方案:挂载到全局(适合小型项目)
如果不想新增模块,可以临时将Lenis实例挂载到window对象(不推荐大型项目使用,避免全局污染):
在main.js中:
const lenis = new Lenis(/* 配置 */) app.provide('lenis', lenis) window.lenis = lenis // 挂载到全局
然后在router的scrollBehavior中直接调用:
scrollBehavior(to, from, savedPosition) { // 直接使用window.lenis window.lenis.scrollTo(...) // 其他逻辑 }
内容的提问来源于stack exchange,提问作者ialphan
相关产品推荐
相关产品推荐

