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:[]
动态添加路由
-
addRouterouter.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回调函数中

浙公网安备 33010602011771号