With the popularity of single page application of front-end SPA, the concept of front-end routing appears in order to realize page hopping without refreshing

The implementation principle of front-end routing

  • Dynamically render different pages by matching different URL paths

Lead up to the problem -url path changes can cause the page to refresh

Solutions:

  • Implemented by changing the hash value

The hash value is the value URL # and the following value

window.location.hash = '/login' // Add #/login to the end of the url
console.log(window.location.hash)  // Print the result #/login
Copy the code
  1. Url path # after the value will not be resolved –> changes will not cause the page to refresh (no new requests will be made)
  2. The window. onHashChange event listens for hash changes
// Work with vue's built-in Component
function updateDom(){match the hash value for the corresponding component switch}window.addEventListener('hashchange',updateDom)
Copy the code
  • Through H5 historyAPI implementation
window.history.pushState(state, title[, url]) 
// state: Data that needs to be saved. This data can be retrieved in event.state when the popState event is triggered
// title: null
// url(optional) : Sets the url for the new history. The origin of the new URL must be the same as the origin of the current URL, otherwise an error will be thrown. A URL can be an absolute path or a relative path.
/ / if the current url is https://www.baidu.com/a/, execution history. PushState (null, null, '/'/qq), as https://www.baidu.com/a/qq/,
/ / execution history. PushState (null, null, '/ qq/'), they become https://www.baidu.com/qq/

window.history.replaceState(state, title, url)
PushState is basically the same as pushState, except that it modifies the current history while pushState creates a new history

window.addEventListener('popstate'.function() {
	// Listen for browser forward and backward events. PushState and replaceState methods do not trigger
});

window.history.back() / / back
window.history.forward() / / to go forward
window.history.go(1) Window. History. Length displays the number of pages in the current history stack
Copy the code

Difference between history and hash

  • Compatibility Hash is more compatible

  • In terms of user requirements, relative hash will add # signs on the path from the appearance, resulting in low user satisfaction

  • History is a directly changed URL, and if the page is refreshed it will return a 404 question, whereas pash does not

    -- Come on!!Copy the code