【问题标题】:Vue2 navigate to external url with location.hrefVue2 使用 location.href 导航到外部 url
【发布时间】:2017-11-19 15:00:46
【问题描述】:

我尝试使用 router.go、router.push、router.replace 和 window.location.href 转到“www.mytargeturl.org”来重定向我的 vuejs 应用程序,但我总是得到 myVueapp.com/www.mytargeturl。组织 这是我的路线:

  routes:[
{path: '/', component: App,
  children:[
    {
      path: 'detail',
      component: ItemDetail,
      props: true
    },
    {
      path: 'search',
      component: Middle
    }       
  ]
},   
{
  path: '/test', component: Test
},
{ path: '/a', redirect: 'www.mytargeturl.org' } // also tried this but didnt work

]

【问题讨论】:

  • 只需使用常规的a 标签。 vue-router 用于在您的应用内导航
  • 这很简单:不要使用 vue-router,因为它会重定向到内部链接(即在应用程序内)。使用 window.location 应该可以正常工作。
  • 在发帖之前我已经尝试过 window.location 但没有成功。这是我的示例:jsfiddle.net/alvirtuoso/dkb1d13h

标签: vue.js vuejs2 vue-router


【解决方案1】:

同意其他cmets的人。 Vue 的理念不是解决已经解决的问题。同样在这里。尽可能使用普通的a 标签作为链接。如果您需要通过路由器,请使用Navigation Guards

{
    path: '/redirect',
    beforeEnter(to, from, next) {
        // Put the full page URL including the protocol http(s) below
        window.location.replace("https://example.com")
    }
}

【讨论】:

  • 这仍然像 myvueapp.com/www.mytargeturl.org 一样在内部指导我
  • 哦,对不起,您需要使用带有协议的完整页面 url,例如google.com
  • 我建议将此详细信息添加到此答案中以使其更清晰
  • 在 Vue 错误 TS2322 (TS) 类型 '"example.com"' 的 Typescript 版本中爆炸不可分配给类型 'Location'。 D:\TFS\EricSandBoxVueTsFromTroy\clientapp\tsconfig.json D:\TFS\EricSandBoxVueTsFromTroy\clientapp\src\router\index.ts 145 活动
  • 谢谢,我已将代码调整为使用location.redirect,我认为它最适合这种情况。
【解决方案2】:

找到了解决方案。通过在我的目标网址中添加 http,一切都很好!像这样 window.location = 'http://mytargeturl.org"

这似乎是普遍的 javascript 真理,而不仅仅是 vue。

【讨论】:

  • 所以你是说{ path: '/a', redirect: 'http://www.mytargeturl.org' } 为你工作?!它不适合我。
【解决方案3】:

在这种情况下不需要使用导航守卫,在路由配置中使用dynamic redirect 更干净

routes:[
  {
    path: '/redirect-example',
    redirect: (to: Route) => {
      window.location.href = 'http://example.com'
      return '/redirecting' // not important since redirecting
    }
  }
]

【讨论】:

  • 在 vueapp 的 typescript 版本中爆炸:D:/TFS/EricSandBoxVueTsFromTroy/clientapp/src/router/index.ts(143,24) 中的错误:143:24 找不到名称“Route”。
  • @Eric Brown 这是一个打字稿,导入类型,或者如果你使用 vanilla 运行,那么完全放弃它
【解决方案4】:

在您的路由中,使用重定向 url 设置元属性

{
  name: "Shop",
  path: "/shop",
  component: {},
  meta: { RedirectExternalUrl: "https://mystore.com" },
},

并设置一个路由器保护功能来完成这项工作:

router.beforeEach(async (to, from, next) => {

    // External redirect
    if (to.matched.some((record) => record.meta.RedirectExternalUrl)) {
        const url: string = to.meta.RedirectExternalUrl as string;
        window.location.replace(url);
        return;
    }

    next();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 2021-03-09
    • 2011-03-18
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    相关资源
    最近更新 更多