You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Vue.js+Quasar项目的Router文件夹index.js中如何获取当前URL?

解决方法

你遇到的无法访问window、拿不到$router的问题,本质是两个常见原因:

  1. 若开启了Quasar SSR/SSG模式,代码会在服务端环境执行,此时没有浏览器全局的window对象
  2. $router是挂载到Vue实例上的全局属性,路由配置文件执行时Vue实例还未完成初始化,自然无法访问该属性

可按照以下方案实现需求:


方案1:在createRouter函数内直接获取(推荐)

Quasar的src/router/index.js默认导出createRouter工厂函数,会自动注入ssrContext等运行时参数,你可以在路由实例创建完成后直接取值:

import { createRouter, createWebHistory, createMemoryHistory } from 'vue-router'
import routes from './routes'

export default function ({ ssrContext }) {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : createWebHistory(process.env.VUE_ROUTER_BASE)

  const router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,
    history: createHistory()
  })

  // 此处即可获取完整URL,自动适配服务端/客户端环境
  let currentUrl = ''
  if (process.env.SERVER) {
    // 服务端从请求上下文取
    const req = ssrContext.req
    currentUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`
  } else {
    // 客户端直接取全局对象,也可通过router实例拼接
    currentUrl = window.location.href
    // 不直接使用window的写法:
    // currentUrl = `${window.location.origin}${router.currentRoute.value.fullPath}`
  }

  // 若需要在路由拦截时获取最新URL,也可以写在beforeEach钩子内
  router.beforeEach((to, from, next) => {
    console.log('当前路由全路径:', to.fullPath)
    next()
  })

  return router
}

方案2:导出router实例供外部文件调用

如果需要在router文件夹下的其他工具文件中获取URL,可以把创建好的router实例导出:

// src/router/index.js 末尾追加
export let routerInstance

export default function ({ ssrContext }) {
  // ...原有创建router的逻辑
  routerInstance = router
  return router
}

其他文件中导入后即可使用:

import { routerInstance } from './index'

// 注意client端router.currentRoute是ref类型,需要取.value
console.log(routerInstance?.currentRoute?.value?.fullPath)

内容的提问来源于stack exchange,提问作者Mohsen Dehghani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:54:04