vue路由实现内部切换
Vue 路由内部切换的实现方法
使用 <router-link> 组件
在模板中使用 <router-link> 组件实现导航,通过 to 属性指定目标路由路径。这种方式会渲染为 <a> 标签,但不会触发页面刷新。
<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>
可以通过 :to 绑定动态路径或命名路由:
<router-link :to="{ name: 'user', params: { id: 123 }}">User</router-link>
编程式导航
通过 this.$router 提供的 API 实现编程式导航:
// 路径字符串
this.$router.push('/home')
// 对象形式
this.$router.push({ path: '/home' })
// 命名路由
this.$router.push({ name: 'user', params: { id: '123' } })
// 带查询参数
this.$router.push({ path: '/user', query: { plan: 'private' } })
使用 replace 方法替换当前路由(不会留下历史记录):
this.$router.replace('/new-path')
路由传参
通过 params 或 query 传递参数:
// params 方式(需在路由配置中定义)
this.$router.push({ name: 'user', params: { userId: '123' } })
// query 方式(URL 显示参数)
this.$router.push({ path: '/user', query: { userId: '123' } })
在目标组件中通过 this.$route.params 或 this.$route.query 获取参数。

路由守卫控制切换
可以使用路由守卫在切换前进行验证或处理:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
动态路由匹配
在路由配置中使用动态路径参数:
const routes = [
{ path: '/user/:id', component: User }
]
在组件中通过 this.$route.params.id 获取参数。

嵌套路由
通过嵌套的 children 配置实现嵌套视图:
const routes = [
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: Profile },
{ path: 'posts', component: Posts }
]
}
]
需要在父组件中添加 <router-view> 来显示子路由。
命名视图
单个路由可以映射多个命名组件:
const routes = [
{
path: '/',
components: {
default: Home,
sidebar: Sidebar
}
}
]
在模板中使用命名视图:
<router-view name="sidebar"></router-view>
<router-view></router-view>






