vue路由实现方式
Vue 路由的实现方式
Vue 路由主要通过 vue-router 库实现,以下是常见的几种实现方式:
基于 vue-router 的基本配置
安装 vue-router 后,在项目中配置路由表:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = new VueRouter({
routes
})
export default router
在入口文件(如 main.js)中注入路由实例:
import router from './router'
new Vue({
router,
render: h => h(App)
}).$mount('#app')
动态路由匹配
通过冒号 : 标记动态路径参数:
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> 标签渲染子路由。
编程式导航
通过 this.$router 的 API 实现跳转:
this.$router.push('/about') // 跳转到指定路径
this.$router.push({ name: 'user' }) // 使用命名路由
this.$router.replace('/login') // 替换当前路由
this.$router.go(-1) // 返回上一页
命名路由与命名视图
为路由或视图分配名称:
const routes = [
{
path: '/settings',
components: {
default: Settings,
sidebar: SettingsSidebar
}
}
]
模板中使用 <router-view name="sidebar"> 指定渲染位置。
路由守卫
通过全局或局部守卫控制导航:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
next('/login')
} else {
next()
}
})
组件内定义守卫:
export default {
beforeRouteEnter(to, from, next) {
// 在渲染前执行逻辑
next()
}
}
路由懒加载
使用动态导入实现按需加载:
const routes = [
{
path: '/dashboard',
component: () => import('./views/Dashboard.vue')
}
]
Hash 模式与 History 模式
配置路由模式:
const router = new VueRouter({
mode: 'history', // 或 'hash'
routes
})
History 模式需服务器端支持,避免刷新 404。
路由元信息
通过 meta 字段传递额外数据:
const routes = [
{
path: '/admin',
meta: { requiresAuth: true }
}
]
滚动行为
自定义页面切换时的滚动位置:
const router = new VueRouter({
scrollBehavior(to, from, savedPosition) {
return { x: 0, y: 0 }
}
})
以上方法覆盖了 Vue 路由的核心使用场景,可根据实际需求组合或扩展。







