3分钟弄懂单路由页面切换跳转渲染原理--浏览器路由 HTML5 History API

126 阅读1分钟

API:

// 参数一:作为event中的状态数据传递到事件监听中
// 参数二:title --- 没用
// 参数三:path ---- 影响地址栏url
window.history.pushState({ path: path }, '', path);

单页面路由跳转的原理就是主动触发pushState,作用一修改地址栏url,作用二是传递事件参数

EventListener:

window.addEventListener('popstate', function (event) {
            console.log(event);
});

popstate不是一个可主动触发的api,是被动触发的事件监听类型。

  • 浏览器的前进、后退,api的history.go()history.back()history.forward()会触发事件

  • 在事件监听回调中,可以拿到pushState传递过来的参数(参数一)。在event.state里面

  • 单页面路由渲染的原理就是,监听popstate,拿到传递过来的数据重新渲染组件,再挂载到dom上。

单路由页面与服务器配合实现的关系:

  • 页面地址栏键入url回车时、刷新时,带路径向服务器请求页面资源。这时需要重定向(try_file)到首页。
  • 拿到首页资源,执行js脚本,renderContent(window.location.pathname),拿着路径匹配渲染相应路由组件。
  • 前进/后退/路由history切换不会请求服务器资源。监听popstate事件,来渲染相应路由组件。window.addEventListener('popstate',(event)=>renderContent(window.location.pathname,event.state))