history实现前端路由

本文介绍了一个简单的使用History API实现的前端路由案例。该案例通过监听浏览器的popstate事件来更新页面内容,并通过JavaScript拦截链接点击事件,手动改变浏览器历史记录,从而实现无刷新页面跳转。需要注意的是,在使用History模式时,必须有服务器的支持。

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

这里要注意有一个坑,就是history模式天然是要服务器支持的,也就是说至少也需要起一个服务器。不然“///”这种样式的路径是不会识别的。

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<a href="/about">about</a>
<a href="/">home</a>
<a href="/test">test</a>
<a href="/about/test">about_test</a>
<div id="app"></div>
<script type="text/javascript">
function Router(routeOption,id){
        this.routes=routeOption;
        this.currentRoute = '';
        this.dom = id ? document.getElementById(id) : null;
    }
    Router.prototype = {
        init(){
            window.addEventListener('popstate', () => {
              this.currentRoute = window.location.pathname;
              this.routes[this.currentRoute] 
                    ? this.dom ? this.dom.innerText = this.routes[this.currentRoute] : null
                    : null;
            })
        },
        _updateState(route){
             window.history.pushState(
                  null,
                  this.routes[route],
                  route
                )
        },
        route(route){
            this._updateState(route);
        }
    }
    let router = new Router({
          '/': 'Home',
          '/about': 'About',
          '/about/test': 'About_test'
        },'app');

    router.init();
    document.querySelectorAll('a').forEach(function(item,index){
        item.addEventListener('click',function(e){
            e.preventDefault();
            let route = item.getAttribute('href');
            router.route(route);
        })
    })
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值