js实现通过window监听pushState和replaceState

前端路由中vue-router的路由变更原理

vue-router可以通过两种模式进行前端路由,哈希模式:

  location.hash='/abc',location.replace('#/def')

  哈希模式哈希值变化可以通过onhashchange监听到,从而渲染响应组件

history模式:

  hostory.pushState(stateObj,'title 1','/abc'),history.replaceState(stateObj,'title 2','/def')

  history模式可以通过对原生pushState和replaceState方法进行封装,主动发出事件实现监听

var _wr = function(type) {
  var orig = history[type];
  return function() {
    var e = new Event(type);
    e.arguments = arguments;
    window.dispatchEvent(e);
    // 注意事件监听在url变更方法调用之前 也就是在事件监听的回调函数中获取的页面链接为跳转前的链接
    var rv = orig.apply(this, arguments);
    return rv;
  };
};
history.pushState = _wr('pushState');
history.replaceState = _wr('replaceState');
window.addEventListener('pushState', function(e) {
  var path = e && e.arguments.length > 2 && e.arguments[2];
  var url = /^http/.test(path) ? path : (location.protocol + '//' + location.host + path);
  console.log('old:'+location.href,'new:'+url);
});
window.addEventListener('replaceState', function(e) {
  var path = e && e.arguments.length > 2 && e.arguments[2];
  var url = /^http/.test(path) ? path : (location.protocol + '//' + location.host + path);
  console.log('old:'+location.href,'new:'+url);
});

 

posted @ 2021-12-08 11:41  ChMao  阅读(945)  评论(0)    收藏  举报