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

VueRouter如何通过beforeEnter定义带查询参数跳转外部链接的路由

报错原因

beforeEnter路由守卫的执行上下文不绑定Vue实例,因此this为undefined,自然无法通过this.$router获取路由参数。

正确写法

beforeEnter守卫默认接收to、from、next三个入参,其中to对象就包含了当前路由的所有查询参数,直接从to.query中取值即可:

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    beforeEnter(to, from, next) {
      // 可选:先判断参数存在,避免拼接无效地址
      if (!to.query.path) {
        next()
        return
      }
      // 对路径参数编码,避免特殊字符导致地址解析错误
      const targetPath = encodeURIComponent(to.query.path)
      // 拼接地址跳转,如果是跨域外部链接直接写完整域名即可
      window.location.href = `/path=${targetPath}`
    },
    name: 'Home',
    component: Home3
  }
]

注意事项

  • 跳转外部链接后不需要再调用next(),页面已经离开当前Vue应用,路由守卫逻辑不需要继续执行
  • 如果参数里包含中文、空格、特殊符号,必须用encodeURIComponent编码,否则地址会出现解析异常

内容的提问来源于stack exchange,提问作者Ueda Takeyuki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:36:08