1. export default function createBrowserHistory() {
    2. const globalHistory = window.history;
    3. let listeners = [];
    4. let initialLocation = {
    5. pathname: window.location.pathname,
    6. state: globalHistory.state,//历史对象上的状态
    7. };
    8. function createHref(location) {
    9. return location.protocol + location.host + location.pathname + location.search + location.hash;
    10. }
    11. function setState(state) {
    12. Object.assign(history, state);
    13. history.length = globalHistory.length;
    14. listeners.forEach(listener => listener());
    15. }
    16. function listen(listener) {
    17. listeners.push(listener);//数组的push方法
    18. }
    19. function push(path, state) {
    20. const action = 'PUSH';
    21. const location = { path, state };
    22. globalHistory.pushState(state, null, path);
    23. setState({ action, location });
    24. }
    25. function go(n) {
    26. globalHistory.go(n);
    27. }
    28. function goBack() {
    29. go(-1);
    30. }
    31. function goForward() {
    32. go(1);
    33. }
    34. function replace(path, state) {
    35. const action = 'REPLACE';
    36. const location = { path, state };
    37. globalHistory.replaceState(state, null, path);
    38. setState({ action, location });
    39. }
    40. let isBlock;
    41. function block(prompt) {
    42. isBlock = prompt;
    43. }
    44. let history = {
    45. length: globalHistory.length,
    46. action: 'POP',//当前路径是怎么来的?
    47. location: initialLocation,
    48. createHref,//通过location对象得到一个路径字符串
    49. push,//跳转到新的路径里去,往历史里添加一个新条目
    50. replace,//跳转到新的路径里去,不会添加新的条目,而是替换当前的条目
    51. go,
    52. goBack,
    53. goForward,
    54. block,
    55. listen
    56. }
    57. return history;
    58. }

    https://www.yuque.com/dahai-gyz0e/tqybqc/uk76g9