vue的路由实现
Vue 路由的实现方式
Vue 路由主要通过 Vue Router 实现,它是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是 Vue 路由的核心实现方法:
安装 Vue Router
通过 npm 或 yarn 安装 Vue Router:
npm install 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
路由挂载
在 Vue 实例中挂载路由:
import router from './router'
new Vue({
router,
render: h => h(App)
}).$mount('#app')
路由视图与导航
在模板中使用 <router-view> 和 <router-link>:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
动态路由与参数传递
动态路径参数
通过 : 定义动态路由参数:
const routes = [
{ path: '/user/:id', component: User }
]
在组件中通过 this.$route.params 获取参数:

export default {
computed: {
userId() {
return this.$route.params.id
}
}
}
编程式导航
通过 this.$router 实现编程式导航:
this.$router.push('/about')
this.$router.replace('/login')
this.$router.go(-1)
嵌套路由
通过 children 配置嵌套路由:
const routes = [
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: Profile },
{ path: 'posts', component: Posts }
]
}
]
在父组件模板中添加 <router-view>:
<div>
<h2>User</h2>
<router-view></router-view>
</div>
路由守卫
通过路由守卫控制导航:

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: '/user', name: 'user', component: User }
]
使用命名视图:
<router-view name="header"></router-view>
<router-view></router-view>
路由模式
支持 hash 和 history 两种模式:
const router = new VueRouter({
mode: 'history',
routes
})
以上是 Vue 路由的核心实现方法,涵盖了从基础配置到高级功能的完整流程。






