vue3学习笔记—vue-router(3)

本文介绍了Vue3中vue-router的两种历史记录模式——Hash模式和HTML5模式,并详细讲解了路由守卫的概念,包括全局守卫、路由独享守卫和组件内守卫。此外,还提到了路由懒加载的优势,它可以在使用时按需加载,提高应用的加载速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不同的历史记录模式

Hash 模式用的是 createWebHashHistory(),不会发送请求到服务器,页面不会刷新,提高性能

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
    // hash 模式
    history: createWebHashHistory(),
    routes, // 'routes: routes' 的缩写
})

HTML5模式用的是 createWebHistory()

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
    //history模式
    history:createWebHistory(),
    routes, // 'routes: routes' 的缩写
})

两种模式的区别就在于页面的URL中有无“#”

路由守卫

to,跳转后的页面

from,跳转前的页面

全局守卫

作用于页面全部路由

router.beforeEach((to,from,next)=>{
    console.log(to);
    console.log(from);
    next()//通行证
})

每路守卫(路由独享)

控制一个路由

    {
        path: '/about', 
        component: About,
        //每路守卫(路由独享)
        beforeEnter: (to, from,next) => {//token
            console.log(to);
            console.log(from);
            if(123 == 123){
                next()
            }
        }
    },

组件内的守卫

<script>
export default {
    data() {
        return {
            age: 18
        }
    },

    beforeRouteEnter(to, from, next) {//拿不到实例对象,通过next回调函数获取
        console.log(to);
        console.log(from);
        next((vm) => {
            console.log(vm.age);
        })

        console.log("路由进去组件之前");
    },

    beforeRouteUpdate() {
        console.log("路由更新组件之前");
    },

    beforeRouteLeave() {
        console.log("路由离开组件之前");
    },
}
</script>

路由懒加载

使用时才会加载,不会和静态导入一样主动加载全部,相比静态导入,速度会更加快。

//静态导入
// import Home from '../views/Home.vue'

//路由懒加载,用到的时候再加载
const Home=()=>import('../views/Home.vue')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值