vue 怎么实现跳转的
vue-router 基本跳转方法
安装 vue-router 后,在项目中配置路由表:
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
声明式导航
在模板中使用 <router-link> 组件实现跳转:
<router-link to="/about">关于我们</router-link>
<router-link :to="{ name: 'About' }">命名路由跳转</router-link>
编程式导航
在组件方法中使用 router 实例进行跳转:
// 字符串路径
this.$router.push('/about')
// 对象形式
this.$router.push({ path: '/about' })
// 命名路由
this.$router.push({ name: 'About' })
// 带查询参数
this.$router.push({ path: '/about', query: { id: 1 } })
// 替换当前路由(不记录历史)
this.$router.replace('/about')
路由传参方式
通过 params 传递参数:
// 路由配置需要定义参数
{
path: '/user/:id',
name: 'User',
component: User
}
// 跳转时传递
this.$router.push({ name: 'User', params: { id: 123 } })
通过 query 传递参数:
this.$router.push({ path: '/user', query: { id: 123 } })
动态路由匹配
路由配置中使用动态字段:
{
path: '/user/:username/post/:post_id',
component: UserPost
}
在组件中获取参数:
this.$route.params.username
this.$route.params.post_id
导航守卫控制跳转
全局前置守卫:
router.beforeEach((to, from, next) => {
// 必须调用 next()
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})
组件内守卫:
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被验证前调用
next(vm => {
// 通过 `vm` 访问组件实例
})
}
路由懒加载
通过动态导入实现路由懒加载:
const UserDetails = () => import('./views/UserDetails.vue')
{
path: '/user/:id',
component: UserDetails
}






