vue路由的实现
Vue 路由的实现
Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是 Vue Router 的核心实现方式和步骤:
安装 Vue Router
通过 npm 或 yarn 安装 Vue Router:
npm install vue-router
或
yarn add vue-router
基本配置
在项目中引入 Vue Router 并配置路由:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = new VueRouter({
routes
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
路由视图
在根组件(通常是 App.vue)中添加 <router-view> 标签,用于渲染匹配的组件:
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
导航链接
使用 <router-link> 组件实现导航:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
动态路由
通过冒号 : 定义动态路由参数:
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.replace('/about')
this.$router.go(-1)
路由守卫
通过路由守卫实现导航控制:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
懒加载路由
通过动态导入实现路由懒加载:
const routes = [
{ path: '/', component: () => import('./views/Home.vue') }
]
路由模式
Vue Router 支持两种路由模式:
hash模式(默认):URL 带#,如http://example.com/#/abouthistory模式:URL 无#,需服务器配置支持
const router = new VueRouter({
mode: 'history',
routes
})
以上是 Vue Router 的核心实现方式,涵盖了从基础配置到高级功能的完整流程。







