Vue-router小知识

296 阅读2分钟

路由懒加载

使用原因

当打包构建应用时, JavaScript包会变得非常大,影响页面加载;将不同路由对应的组件分割成不同的代码块,当路由被访问的时候才加载对应组件,会更加搞笑,也可以提高首屏的渲染效率

实操

   const routes = [
       { path: '/home', component: () => import('../pages/Home.vue')}
   ]

NotFound

动态路由匹配所有notfound页面

  • 方法一

/:pathMatch(.*)

   const routes = [
        { path: '/:pathMatch(.*)', component: () => import('../pages/404.vue') }
    ]
  • 方法二

/:pathMatch(.*)*

   const routes = [
        { path: '/:pathMatch(.*)*', component: () => import('../pages/404.vue') }
    ]

通过$route.params.pathMatch获取到传入的参数

    <h2>Not Found {{ $route.params.pathMatch }}</h2>
  • 方法一

image.png

  • 方法二

image.png

方法一和方法二的区别:是否解析 /

代码的页面跳转

    this.$router.push(/xxx)
    this.$router.push({
        path: '/xxx'
    })
  • setup中
    const router = useRouter()
    const jumpToXXX = () => {
        router.replace('/xxx')
    }

query方式的参数

    this.$router.push({
        path: '/xxx',
        query: { name: 'why', age: 18 }
    })
    // 获取
    const info = this.$route.query

操作

  • replace
  • go
  • back
  • forward

动态添加路由

addRoute

一级路由

    // 动态添加一个路由
    const categoryRoute = {
        path: '/category',
        component: () => import('../pages/Category.vue')
    }
    router.addRoute(categoryRoute)

二级路由(children路由)

    // 父级的name: 'home'
    // 动态添加一个路由
    const HomeMomemnt = {
        path: 'moment',
        component: () => import('../pages/HomeMomemnt.vue')
    }
    router.addRoute('home', HomeMomemnt)

再深的路由可直接加入children中,一般不会超过3级

动态删除路由

添加一个name相同的路由

router.addRoute({path: '/about', name: 'about', component: About })
// 名字唯一
router.addRoute({path: '/other', name: 'about', component: Home })

通过removeRoute方法,传入路由的名称

    router.addRoute({path: '/about', name: 'about', component: About })
    // 删除
    router.removeRoute('about')

通过addRoute方法的返回值回调

    const removeRoute = router.addRoute(routeRecord)
    removeRoute() // 删除路由如果存在的话

检查路由是否存在

router.hasRoute()

获取一个包含所有路由记录的数组

router.getRoutes()

路由导航守卫

vue-router提供的导航守卫主要用来通过跳转或取消的方式守卫导航

beforeEach

参数

  • to
  • from

返回值

  • false
  • 不返回或者undefined:进行默认导航
  • 返回一个路由地址
    • 可以是一个string类型的路径
    • 可以是一个对象,对象中包含path、query、params等
    router.beforeEach((to, from) => {
       if (to.path.indexOf('/home' !== -1) {
           return '/login'
       }
    })
    router.beforeEach((to, from) => {
       if (to.path != '/login') {
           consttoken= window.localStorage.getItem('token')
           if (!token) {
               return '/login'
           }
       }
    })
    export default {
        setup() {
            const router = useRouter()
            const login = () => {
                window.localStorage.setItem('token', '123456')
                router.push({
                    path: '/home'
                })
            }
            return {
                login
            }
        }
    }

可选的第三个参数:next

  • Vue2中通过next函数来决定如何进行跳转
  • Vue3中通过返回值来控制,不再推荐使用next函数(因为开发中很容易调用多次next)

image.png

Vue-router