vue router实现方式
Vue Router 的实现方式
Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是几种常见的实现方式:
基本路由配置
在 Vue 项目中安装 Vue Router 后,可以通过 routes 数组定义路由规则。每个路由映射到一个组件。
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
动态路由匹配
通过冒号 : 标记动态路径参数,可以在组件中通过 $route.params 访问。
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.push、router.replace 等方法实现页面跳转,而非依赖 <router-link>。
// 字符串路径
router.push('/home')
// 对象形式
router.push({ path: '/home' })
// 带查询参数
router.push({ path: '/user', query: { id: '123' } })
路由守卫
通过全局或路由独享的守卫控制导航行为,例如权限验证。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
路由懒加载
通过动态导入组件实现懒加载,优化首屏加载速度。
const routes = [
{ path: '/about', component: () => import('./views/About.vue') }
]
命名路由和命名视图
通过 name 属性为路由或视图组件命名,便于跳转或渲染。
const routes = [
{
path: '/settings',
components: {
default: Settings,
sidebar: Sidebar
}
}
]
路由元信息
通过 meta 字段定义路由的元信息,例如页面标题或权限要求。
const routes = [
{ path: '/admin', meta: { requiresAdmin: true } }
]
以上是 Vue Router 的常见实现方式,根据项目需求选择合适的方法组合使用。







