前端vue实现页面跳转
路由配置
在Vue项目中,页面跳转通常通过Vue Router实现。需要在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>组件实现跳转,通过to属性指定目标路径:
<router-link to="/about">跳转到关于页</router-link>
可通过:to绑定动态路径:
<router-link :to="{ path: '/user', query: { id: 123 } }">用户页</router-link>
编程式导航
在JavaScript代码中使用router.push()方法跳转:
// 基本跳转
this.$router.push('/about')
// 带参数跳转
this.$router.push({ path: '/user', query: { id: 1 } })
// 命名路由跳转
this.$router.push({ name: 'user', params: { userId: '123' } })
路由传参
通过动态路由传递参数:
// 路由配置
{ path: '/user/:id', component: User }
// 获取参数
this.$route.params.id
通过查询参数传递数据:
// 跳转时传递
this.$router.push({ path: '/search', query: { keyword: 'vue' } })
// 获取查询参数
this.$route.query.keyword
导航守卫
可在路由跳转前后执行逻辑控制:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
动态路由
通过addRoute方法动态添加路由:
router.addRoute({
path: '/admin',
component: AdminPanel
})
路由懒加载
使用动态导入实现组件懒加载:
const User = () => import('../views/User.vue')
路由模式切换
根据需求选择路由模式:
const router = createRouter({
history: createWebHashHistory(), // 带#的hash模式
// 或
history: createWebHistory(), // 不带#的history模式
routes
})






