vue路由实现原理总结

1.vue路由的两种模式

hash模式:
比如 'http://www.baidu.com/#/abc'  hash 的值为 '#/abc'  
它的特点在于:hash 虽然出现 URL 中,但不会被包含在 HTTP 请求中,因此改变 hash 不会重新加载页面
但是会触发 onhashchange 事件,所以我们可以监听,然后渲染自己要渲染的组件,达到路由的效果

history模式: 
通过 HTML5 中新增的 pushState() replaceState() 方法
应用于浏览器的历史记录,在已有的 go(),back(),forward() 的基础之上,它们提供了对历史记录进行修改的功能
当它们执行修改时,虽然改变了当前的 URL,但你浏览器不会立即向后端发送请求
我们可以通过 onpopstate 事件,监听 history 的变化,然后渲染自己要渲染的组件,达到路由的效果

2.pushState和replaceState的用法

history.pushState(state, title, url)
// 作用:将当前URL和history.state加入到history中,并用新的state和URL替换当前。不会造成页面刷新
// state:与要跳转到的URL对应的状态信息
// title:新页面的标题,但是所有浏览器目前都忽略这个值
// url:要跳转到的URL地址,不能跨域

history.replaceState(state, title, url) 
// 作用:pushState的区别就在于它不是写入而是替换修改浏览历史中当前纪录,其余和 pushState一模一样

3.实现原理

<div>
    <h2>history</h2>
    <a class="history">home1</a>
    <a class="history">about1</a>
    <h2>hash</h2>
    <a class="hash">home2</a>
    <a class="hash">about2</a>
</div>
window.onload = function(){
        // history  注册路由
        document.querySelectorAll('.history').forEach(item => {
            item.addEventListener('click', e => {
                e.preventDefault();
                let link = item.textContent;
                window.history.pushState({
                    name: 'api'
                }, '', link);
            })
        });
        // 监听路由,popstate监听history变化,可以使用history.go() history.forward()使history变化,触发事件
        window.addEventListener('popstate', (e) => {
            console.log({
                location: location.href,
                state: e.state
            })
        });

        // hash  注册路由
        document.querySelectorAll('.hash').forEach(item => {
            item.addEventListener('click', e => {
                e.preventDefault();
                let link = item.textContent;
                location.hash = link;
            }, false)
        });
        // 监听路由
        window.addEventListener('hashchange', () => {
            console.log({
                location: location.href,
                hash: location.hash
            })
        }, false)
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值