我想在Vue.js
中进行类似于原生JavaScript的重定向。
window.location.href = 'some_url'
我该如何在Vue.js中实现这个?
我想在Vue.js
中进行类似于原生JavaScript的重定向。
window.location.href = 'some_url'
我该如何在Vue.js中实现这个?
router.push(path)
以编程方式导航到任何特定路由(请注意,在Vue 2之前,这是router.go(path)
)。$router
属性中访问,这意味着您可以使用this.$router.push(path)
从组件内部访问push
。
// object
router.push({ path: 'home' })
// named route
router.push({ name: 'user', params: { userId: '123' } })
// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' } })
// with hash, resulting in /about#team
router.push({ path: '/about', hash: '#team' })
除了Vue路由器之外,window.location.href = 'some url';
对于非单页面应用程序也可以正常工作。
如果您正在寻找更加永久的重定向,而不仅仅是程序导航,例如将所有example.com/foo
点击重定向到example.com/bar
,那么您应该使用Vue Router的redirect或alias功能。
重定向在路由配置中进行设置,让您告诉Vue Router始终将给定路径重定向到其他地方,例如导航到/foo
会将您弹回到/bar
:
const routes = [{ path: '/foo', redirect: '/bar' }];
const routes = [{ path: '/foo/:subPath*', redirect: '/bar/:subPath*' }];
// example.com/foo/profile?id=123 --> example.com/bar/profile?id=123
别名 类似于重定向,可以将流量从一个位置路由到另一个位置,但它们不会更改用户的URL。这样可以通过允许您将UI结构的任意部分映射到任何路径来提供更大的灵活性。
来自文档:
const routes = [
{
path: '/users',
component: UsersLayout,
children: [
// this will render the UserList component for these 3 URLs:
// - /users
// - /users/list
// - /people
{ path: '', component: UserList, alias: ['/people', 'list'] },
],
},
]
routename
的目标路由。 - ka_linthis.$router.push({ name: 'routename' })
对我有效。 - Osh Mansorthis.$router
例如:如果您想在满足条件后重定向到名为“首页”的路由:
this.$router.push('Home')
this.$router.push({name: 'router-name'})
。 - Hamidreza Ghanbari只需使用:
window.location.href = "http://siwei.me"
不要使用vue-router,否则会被重定向到 "http://yoursite.com/#!/http://siwei.me"
我的环境:node 6.2.1、vue 1.0.21、Ubuntu。
当在组件脚本标签中时,您可以使用路由并像这样执行操作。
this.$router.push('/url-path')
如果你想要导航到另一个页面,请使用这个。
this.$router.push({path: '/pagename'});
如果您想带参数转到另一个页面,请使用此选项。
this.$router.push({
path: '/pagename',
params: {
param1: 'value1',
param2: 'value2'
}
});
param
没有起作用,但 params
对我有效。 - Mironreturn router.push({ name: 'publisher-slots' });
用于表单提交成功后的跳转。 - lincolndu一个非常简单的路由:
this.$router.push('Home')
也可以尝试这个...
router.push({ name: 'myRoute' })
如果有人想要将一个页面/a
永久重定向到另一个页面/b
我们可以使用router.js
中添加的redirect:
选项。例如,如果我们想要在用户输入根或基本URL /
时始终将其重定向到另一页:
const router = new Router({
mode: "history",
base: process.env.BASE_URL,
routes: [
{
path: "/",
redirect: "/someOtherPage",
name: "home",
component: Home,
// () =>
// import(/* webpackChunkName: "home" */ "./views/pageView/home.vue"),
},
]
window.location = url;
'url'是您想要重定向的网页链接。
所以,我只是在寻找在哪里放置 window.location.href
,我的结论是最好和最快的重定向方式是在路由中(这样,在重定向之前我们不需要等待任何内容加载)。
像这样:
routes: [
{
path: "/",
name: "ExampleRoot",
component: exampleComponent,
meta: {
title: "_exampleTitle"
},
beforeEnter: () => {
window.location.href = 'https://www.myurl.io';
}
}]