js 实现前端路由的方法
js 实现前端路由的方法
前端路由原理
History API
https://developer.mozilla.org/en-US/docs/Web/API/History_API
https://developer.mozilla.org/en-US/docs/Web/API/History
length (read only)
scrollRestoration (auto or manual)
state (read only)
window.history.back();
window.history.go(-1);
window.history.forward();
window.history.go(1)
window.history.pushState()
window.history.replaceState()
// no need window
history.back();
history.go(-1);
history.forward();
history.go(1)
history.pushState()
history.replaceState()
https://developer.mozilla.org/en-US/docs/Web/API/Window/history
https://developer.mozilla.org/en-US/docs/Web/API/History_API/Working_with_the_History_API
https://developer.mozilla.org/en-US/docs/Web/API/History/pushState
https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState
let stateObj = {
foo: "bar",
};
history.pushState(stateObj, "page 2", "bar.html");
history.replaceState(stateObj, "page 3", "bar2.html");
popstate
https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event
popstate
window.addEventListener('popstate', (event) => {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
});
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null"
history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}
onpopstate
window.onpopstate = function(event) {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null"
history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}"
hash router
hashchange
https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event
window.addEventListener('hashchange', function() {
console.log('The hash has changed!')
}, false);
function locationHashChanged() {
if (location.hash === '#cool-feature') {
console.log("You're visiting a cool feature!");
}
}
window.onhashchange = locationHashChanged;
refs
client-side routing
https://krasimirtsonev.com/blog/article/deep-dive-into-client-side-routing-navigo-pushstate-hash
https://juejin.im/post/6844903842643968014
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13676478.html
未经授权禁止转载,违者必究!