Vue路由重定向方法
Vue路由提供了几种方法进行重定向:
- 使用
redirect
重定向 - 使用
next
函数重定向 下面是使用redirect
进行重定向的代码示例:
// 在路由配置中设置重定向
{
path: '/home',
redirect: '/'
}
其中,path
指定被重定向的页面路径,redirect
指定重定向的页面路径。
下面是使用next
函数进行重定向的代码示例:
// 在路由拦截中使用next进行重定向
router.beforeEach((to, from, next) => {
if (to.path === '/login') {
next()
} else {
const token = localStorage.getItem('token')
if (!token) {
next('/login')
} else {
next()
}
}
})
其中,to
表示目标路由对象,from
表示源路由对象,next
函数用于进行重定向。如果在路由拦截中使用next
函数进行重定向,需要在to.path
判断后再进行next('/login')
跳转操作。
Vue3路由重定向
在Vue3中,路由的实现方式有了较大的变化。Vue3使用的是强大的Composition API,可以通过useRoute()
和useRouter()
来获取路由和重定向。
下面是Vue3路由重定向的代码示例:
import { useRoute, useRouter } from 'vue-router'
export default {
setup() {
const route = useRoute()
const router = useRouter()
function redirectToLogin() {
router.push('/login')
}
return {
route,
redirectToLogin
}
}
}
其中,useRoute()
用于获取当前路由对象,useRouter()
用于获取路由对象,可以使用push()
方法进行路由跳转。
Vue路由重定向配置
在Vue路由中,可以通过对象的方式进行路由重定向的配置。下面是一个简单的代码示例:
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
component: Home
}
]
})
其中,routes
是一个数组,每个元素都是一个路由对象。可以设置path
、component
、redirect
等路由属性,以达到路由跳转的目的。
Vue 重定向
Vue提供了this.$router.push()
和this.$router.replace()
方法用于进行页面的跳转,它们都可以实现路由重定向的效果:
// 使用push进行重定向
this.$router.push('/home')
// 使用replace进行重定向
this.$router.replace('/home')
其中,push
方法可以通过back
进行页面回退,而replace
方法不具备回退功能。
Vue路由redirect
在Vue中,可以使用redirect
属性对路由进行重定向,例如下面的代码:
const router = new VueRouter({
routes: [
{ path: '/a', redirect: '/b' },
{ path: '/b', component: B }
]
})
如果当前路径为/a
,则会自动跳转到/b
页面。
Vue 路由 path
在Vue中,可以使用path
属性指定路由的路径,例如下面的代码:
const router = new VueRouter({
routes: [
{ path: '/home/:id', component: Home }
]
})
使用:id
占位符可以动态地获取路由参数,例如/home/123
可以获取到参数为123。
Vue路由重定向携带参数
在Vue中,可以使用redirect:name
配置项来进行路由重定向和携带参数的操作。
下面是使用redirect:name
进行路由重定向携带参数的代码示例:
const router = new VueRouter({
routes: [
{ path: '/home/:id', component: Home },
{ path: '/user/:id', redirect: to => {
const { id } = to.params
return `/home/${id}`
}
}
]
})
当访问/user/123
路径时,会将路由重定向到/home/123
页面,并携带参数。
Vue路由重定向其他地址
在Vue中,可以使用特殊的路径进行路由重定向到其他地址,例如下面的代码:
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', redirect: 'https://www.baidu.com' }
]
})
当访问任意不存在的路径时,会自动跳转到https://www.baidu.com
页面。
Vue路由重定向命令
在Vue中,可以使用this.$router.go()
命令进行路由的跳转,在传入不同的参数时,具有不同的跳转效果。
下面是使用this.$router.go()
进行路由重定向的代码示例:
// 跳转到上一个历史页面
this.$router.go(-1)
// 跳转到下一个历史页面
this.$router.go(1)
// 跳转到任意一个历史页面
this.$router.go('back')
其中,-1
表示跳转到上一个历史页面,1
表示跳转到下一个历史页面,'back'
表示跳转到任意一个历史页面。