Implementation principles of front-end route hash and history
A, the hash
-
Hash is implemented by concatenating a hash value after the URL to generate a route, such as #/home, after the page URL
-
Code implementation
<div> <! -- Two hyperlinks, Use hash to change url - > < a href = "# / home" > home page < / a > < a href = "# / about" > about < / a > < / div > < div class = "routerView" > < / div > < script > Window.addeventlistener ("hashchange",(e) => {// console.log(" hashchange", location.hash,e); Switch (location.hash){case "#/home": console.log("#/home",document.getElementsByClassName("routerView")); Document. The getElementsByClassName (" routerView ") [0]. The innerText = "home page"; break; case "#/about": console.log("#/about",document.getElementsByClassName("routerView")); Document. The getElementsByClassName (" routerView ") [0]. The innerText = "on"; } }) </script>Copy the code
-
Explanation: #/home and #/about are defined by the href attribute of the A tag. In js, we listen for the hashchange event to listen for the hashchange of the page. When the change occurs, we get the hash of the current route, and obtain the value of the current page through location.hash. Then determine what should be rendered by judging the value of the current hash.
-
Changing the route with a hash will result in # in the browser URL, which is different from the actual route
Second, the history
1. Basic operations
-
History is a new API in HTML5 that, starting with H5, allows developers to call the browser’s History line stack. You can add, delete, change and check the stack.
-
Jump back
window.history.back(); // This is the same as when the user clicks the browser back buttonCopy the code
-
A forward jump
window.history.foeward(); // This is the same as when the user clicks the browser forward buttonCopy the code
-
Jump to a page specified in the HiStor stack (marked 0 by the current page, 1 by forward, -1 by backward)
window,history.go(-1); Back () window.history.go(1); // Jumping to the previous page of the current page is equivalent to calling forwardCopy the code
-
Gets the length of the history stack
let numberOfEntries = window.history.length; Copy the code
2. Modify and add entries to historical records
-
pushState
<script> /** * Add a history to the history stack * @params state Add a state to the history stack * @params titlet */ window.history.pushState(state,title,href); </script>Copy the code
-
popState
Every time the active history item changes, the PopState event is passed to the Window object. If the active history item was created by pushState or changed by replaceState, the state property of the POPState event contains a copy of the current history state object.
-
replaceState
window.history.replaceState(); // Modify the pageCopy the code