前端路由的核心就在於更改url,頁面不刷新,如何做到這一點呢?
第一種方法是改變url的hash值。
location.href
>>> http://localhost:8080/#
location.hash = 'foo'
>>> http://localhost:8080/#/foo
改變hash值,頁面不刷新,頁面會根據前端的路由映射關係找到相應的組件數據並呈現。
第二種方式是使用HTML5的history模式
#1 pushState()與back()
location.href
>>> http://localhost:8080
history.pushState({},'','foo')
>>> http://localhost:8080/foo
history.pushState({},'','about')
>>> http://localhost:8080/about
history.pushState({},'','bar')
>>> http://localhost:8080/bar
history.back()
>>> http://localhost:8080/about
history.back()
>>> http://localhost:8080/foo
把url看做一個棧,pushState()向棧中放入一個url,而back()刪除掉棧頂的url,頁面總是呈現棧頂的url。
這種方式保留了歷史記錄,頁面可以返回。
#2 replaceState()
location.href
>>> http://localhost:8080
history.replaceState({},'','home')
>>> http://localhost:8080/home
history.replaceState({},'','about')
>>> http://localhost:8080/about
直接改變了url,這種方式沒有保存歷史記錄,頁面不可返回。
#3 go()與forward()
//這兩個方法一般與pushState()結合使用
//pushState()會使瀏覽器保留一個url的歷史記錄,而go()方法與forward()方法都可以改變這個歷史記錄的狀態
history.go(-1) 等價於 history.back()
history.go(1) 等價於 history.forward()
history.go(-2)
history.go(2)
...