路由hash、history

hash模式主要是onhashChange事件监听url上#后面(锚点)的改变,控制页面的改变

<body>
    <a href="#/home">go Home</a>
    <a href="#/about">go about</a>
    <a href="#/404">go about</a>
    <div id="router-view"></div>
    <script>
        const routes = [{
                path: '/home',
                component: '<div>This is Home</div>'
            },
            {
                path: '/about',
                component: '<div>This is about</div>'
            },
        ]
        function renderCom(path) {
            const newRoute = routes.filter(item => {
                return item.path === path
            })
            document.getElementById('router-view').innerHTML = newRoute[0] ? newRoute[0].component : ''
        }

        // 处理刷新
        console.log(window.location.href);
        let firstHref = window.location.href
        let firstPath = firstHref.substring(
            firstHref.indexOf('#/') + 1
        )
        if (firstPath) {
            console.log('进来');
            renderCom(firstPath)
        }
        
        window.onhashchange = function (ev) {
            console.log(ev);
            let newPath = ev.newURL.substring(
                ev.newURL.indexOf('#/') + 1
            )
            console.log(newPath);
            renderCom(newPath)
        }
    </script>
</body>

history模式通过HTML5中的两个API,history的pushState和popState方法修改url但不触发页面的跳转,url的改变会触发popState事件,监听该事件也可以实现根据不同的url渲染对应的页面内容
但是因为没有#会导致用户在刷新页面的时候,还会发送请求到服务端,为避免这种情况,需要每次url改变的时候,都将所有的路由重新定位到跟路由下

<body>
    <a href="javascript:pageTo('/home')">go Home</a>
    <a href="javascript:pageTo('/about')">go about</a>
    <a href="javascript:pageTo('/home')">go about</a>
    <div id="router-view"></div>
    <script>
        const routes = [{
                path: '/home',
                component: '<div>This is Home</div>'
            },
            {
                path: '/about',
                component: '<div>This is about</div>'
            },
        ]

        function renderCom(path) {
            alert(path)
            const newRoute = routes.filter(item => {
                return item.path === path
            })
            document.getElementById('router-view').innerHTML = newRoute[0] ? newRoute[0].component : ''
        }
        function pageTo(path) {
            console.log(path);
            //history模式利用pushState重写页面的URL,但是不触发页面的跳转 
            history.pushState({},'标题',path)
            renderCom(path)
        }

		window.addEventListener("popState", function (e) {
            console.log('555',e);
            alert(e)
        })
    </script>
</body>

history模式通过http-server插件本地服务测试,

npm install http-server -g
http-server -c-1   (只输入http-server的话,更新了代码后,页面不会同步更新)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值