vue 实现跳转
路由跳转(Vue Router)
在 Vue 项目中,通常使用 Vue Router 实现页面跳转。确保已安装并配置 Vue Router。
安装 Vue Router
npm install vue-router
配置路由
在 src/router/index.js 中配置路由:
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
声明式导航
在模板中使用 <router-link> 实现跳转:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
编程式导航
在组件方法中使用 router.push 实现跳转:
methods: {
goToAbout() {
this.$router.push('/about')
}
}
动态路由跳转
通过参数传递实现动态路由跳转。
配置动态路由
const routes = [
{ path: '/user/:id', component: User }
]
跳转到动态路由
this.$router.push('/user/123')
获取路由参数 在目标组件中获取参数:
this.$route.params.id
命名路由跳转
通过路由名称实现跳转,便于维护。
配置命名路由
const routes = [
{ path: '/user/:id', name: 'user', component: User }
]
跳转到命名路由

this.$router.push({ name: 'user', params: { id: 123 } })
路由传参
除了动态路由参数,还可以通过查询参数传递数据。
传递查询参数
this.$router.push({ path: '/about', query: { name: 'test' } })
获取查询参数
this.$route.query.name
路由重定向
在路由配置中设置重定向。
配置重定向
const routes = [
{ path: '/home', redirect: '/' }
]
路由守卫
通过路由守卫控制跳转逻辑。
全局前置守卫

router.beforeEach((to, from, next) => {
// 跳转前逻辑
next()
})
组件内守卫
beforeRouteEnter(to, from, next) {
// 组件进入前逻辑
next()
}
外部链接跳转
跳转到非 Vue 路由的外部链接。
使用 window.location
window.location.href = 'https://example.com'
使用 <a> 标签
<a href="https://example.com" target="_blank">External Link</a>
跳转回退
返回上一页或指定页数。
返回上一页
this.$router.go(-1)
返回首页
this.$router.push('/')






