history实现前端路由

来源:互联网 发布:淘宝联盟身份认证 编辑:程序博客网 时间:2024/04/28 08:49

这里要注意有一个坑,就是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>
原创粉丝点击