Vue2 navigate to external url with location.href

雨燕双飞 提交于 2019-12-21 07:29:55

问题


I tried to go to 'www.mytargeturl.org' using router.go, router.push, router.replace and window.location.href to redirect my vuejs app but i always get myVueapp.com/www.mytargeturl.org Here's my route:

  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

]


回答1:


Agreed with people in the comments. Vue's philosophy is not to solve already solved problems. Same here. Just use ordinary a tag for the link whenever possible. If you need to go through the router though, use Navigation Guards

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



回答2:


Found the solution. By adding http in my target url, all is well! Like this window.location = 'http://mytargeturl.org"

This seems to be universal javascript truth not just vue.




回答3:


No need to use navigation guards in this case, cleaner to use dynamic redirect right there in route config

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


来源:https://stackoverflow.com/questions/44595929/vue2-navigate-to-external-url-with-location-href

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!