我想在Vue.js中做一个类似于香草javascript的重定向
window.location.href = 'some_url'
我如何在Vue.js中实现这一点?
我想在Vue.js中做一个类似于香草javascript的重定向
window.location.href = 'some_url'
我如何在Vue.js中实现这一点?
当前回答
根据文件,是路由器。推送似乎是首选方法:
要导航到不同的URL,使用router.push。此方法将 历史堆栈中的新条目,因此当用户单击浏览器时 返回按钮,他们将被带到以前的URL。
来源:https://router.vuejs.org/en/essentials/navigation.html
供参考:Webpack和组件设置,单页应用程序(通过Main.js导入路由器),我必须调用路由器函数,这样说:
this.$router
示例:如果你想在满足条件后重定向到一个名为“Home”的路由:
this.$router.push('Home')
其他回答
如果你正在使用vue-router,你应该使用router.go(path)来导航到任何特定的路由。路由器可以在组件中使用。$router来访问。
否则,window.location.href = 'some url';适用于非单页应用程序。
编辑:router.go()在VueJS 2.0中更改。你可以使用$router。Push ({name: "yourroutename"})或者只是router.push("yourroutename")现在重定向。
文档
注意:在控制器中使用:this.$router。Push ({name: 'routename'})
所以,我所寻找的只是在哪里放window.location.href和结论,我来的是,最好和最快的方式重定向是在路由(这样,我们不等待任何东西加载之前,我们重定向)。
是这样的:
routes: [
{
path: "/",
name: "ExampleRoot",
component: exampleComponent,
meta: {
title: "_exampleTitle"
},
beforeEnter: () => {
window.location.href = 'https://www.myurl.io';
}
}]
也许它会帮助别人。
为了与您最初的要求保持一致:
window.location.href = 'some_url'
你可以这样做:
<div @click="this.window.location='some_url'">
</div>
注意,这并没有利用Vue的路由器,但如果你想“在Vue.js中做一个类似于香草javascript的重定向”,这是可行的。
window.location = url;
'url'是你想重定向的web url。
我使用Vue3,这对我来说是有效的
router.push({ name: 'myRoute' })