Vue路由

路由介绍

映射表,决定数据的流向

页面不刷新的方式

  1. hash,监听hashchange事件
  2. histroy模式:六种模式
    1. pushState
    2. replaceState
    3. popState
    4. go
    5. forward
    6. back

vue-router

基本使用

  1. 安装vue-router
  2. 创建路由对象
    1. history
      1. createWebHashHistory
      2. createWebHistory
    2. routes
      1. path
        1. 动态路由:path:"/home/:id"
        2. /home/123
        3. 获取id:
          1. 模板中:{{ $route.params.id }}
          2. import {useRoute} from 'vue-router' --- useRoute().params.id
      2. component
      3. redirect
      4. name: 独一无二的
      5. meta: 对象 ,给路由带参数
  3. app.use(router)
  4. router-view
  5. router-link
    1. to
      1. 字符串
      2. 对象
        1. path
    2. replace
    3. active-class: 激活的样式
    4. exact-active-class: 精确匹配
  6. 分包
    1. const Home = () => import(/*webpackChunkName: '分包的名称'*/, './views/Home.vue')
  7. 错误显示
    1. path:'/:patchMatch(.*)', component:xxxx
    2. :patchMatch(.*):
    3. :patchMatch(.*)*: 将小路径解析成数组
  8. 路由嵌套
    1. 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 },

导航解析流程

  1. 导航被触发
  2. 失活组件中beforeRouteLeave被调用
  3. 调用beforeEach
  4. 调用重用组件的beforeRouteUpdate
  5. 调用路由配置中的beforeEach
  6. 解析异步路由组件
  7. 被激活的组件中调用beforeRouterEnter
  8. 调用全局的beforeResolve:异步组件被解析,但还没有进行跳转
  9. 路由跳转被确认
  10. 调用全局的afterEach
  11. 触发组件的更新
  12. 组件中beforeRouterEnter 组件实例被注入到next回调函数中
posted @ 2023-03-25 23:16  转角90  阅读(15)  评论(0编辑  收藏  举报