hash前端路由,無刷新html
history 會去請求接口前端
vue 是漸進式前端開發框架,爲了實現 SPA ,須要引入前端路由系統(vue-router)。前端路由的核心是:改變視圖的同時不會向後端發出請求。vue
爲了達到這一目的,瀏覽器提供了 hash 和 history 兩種模式。html5
所以能夠說, hash 模式和 history 模式都屬於瀏覽器自身的屬性,vue-router 只是利用了這兩個特性(經過調用瀏覽器提供的接口)來實現路由。vue-router
實現的原理:後端
pushState()、replaceState() 方法接收三個參數:stateObj、title、url。
// 設置狀態
history.pushState({color: "red"}, "red", "red");
// 監聽狀態
window.onpopstate = function(event){
console.log(event.state);
if(event.state && event.state.color === "red"){
document.body.style.color = "red";
}
}
// 改變狀態
history.back();
history.forward();複製代碼
應用場景:api
經過 pushState 把頁面的狀態保存在 state 對象中,當頁面的 url 再變回到這個 url 時,能夠經過 event.state 取到這個 state 對象,從而能夠對頁面狀態進行還原,如頁面滾動條的位置、閱讀進度、組件的開關等。瀏覽器
調用 history.pushState() 比使用 hash 存在的優點:bash
劣勢:服務器
參考:https://blog.csdn.net/majunjie2017/article/details/78507551