Vue路由
路由介绍
映射表,决定数据的流向
页面不刷新的方式
- hash,监听
hashchange
事件- histroy模式:六种模式
- pushState
- replaceState
- popState
- go
- forward
- back
vue-router
基本使用
- 安装vue-router
- 创建路由对象
- history
- createWebHashHistory
- createWebHistory
- routes
- path
- 动态路由:path:"/home/:id"
- /home/123
- 获取id:
- 模板中:{{ $route.params.id }}
- import {useRoute} from 'vue-router' --- useRoute().params.id
- component
- redirect
- name: 独一无二的
- meta: 对象 ,给路由带参数
- app.use(router)
- router-view
- router-link
- to
- 字符串
- 对象
- path
- replace
- active-class: 激活的样式
- exact-active-class: 精确匹配
- 分包
- const Home = () => import(/*webpackChunkName: '分包的名称'*/, './views/Home.vue')
- 错误显示
- path:'/:patchMatch(.*)', component:xxxx
- :patchMatch(.*):
- :patchMatch(.*)*: 将小路径解析成数组
- 路由嵌套
- children:[]
动态添加路由
-
addRoute
router.addRoute({ path:'/home', component:()=>import(/*webpackName:'home'*/,Home) }) // 指定name 二级路由 router.addRoute('父路由的name',{ path:'/vip', component:()=>import(/*webpackName:'vip'*/,HomeVip) })
-
删除路由
//方式一:添加一个name相同的路由 router.addRoute({path:'/about',name:'about',component:()=>import(About)}) router.addRoute({path:'/about1',name:'about',component:()=>import(About1)}) // 方式二: removeRoute name router.removeRoute('about')
-
hasRoute
: 检查路由是否存在 -
getRoute
: 获取所有路由
导航守卫
//实例
router.beforeEach((to,from,next)=>{
if (to.path!=='/login'){
return '/login'
}
})
钩子函数:
beforeEach
:前置守卫afterEach
:后置守卫
属性:
-
to
-
from
-
next:
vue2中是通过next进行跳转的
vue3是通过返回值进行跳转的
返回值:
- false: 取消当前导航
- 不返回或者undefined: 进行默认导航
- 返回一个路由地址:
- 字符串
- 对象(path,query,params)
组件内
beforeRouteLeave
beforeRouteUpdate
beforeRouteEnter
参数
to
from
next:
next((vm)=>console.log(vm))
全局
beforeEach
afterEach
路由独享
beforeEnter
: (to, from) => { // reject the navigation return false },
导航解析流程
- 导航被触发
- 在失活组件中
beforeRouteLeave
被调用 - 调用
beforeEach
- 调用重用组件的
beforeRouteUpdate
- 调用路由配置中的
beforeEach
- 解析异步路由组件
- 在被激活的组件中调用
beforeRouterEnter
- 调用全局的
beforeResolve
:异步组件被解析,但还没有进行跳转 - 路由跳转被确认
- 调用全局的
afterEach
- 触发组件的更新
- 组件中
beforeRouterEnter
组件实例被注入到next回调函数中
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署