1. 程式人生 > >vue的兩種路由模式原理

vue的兩種路由模式原理

1、hash模式:原理是onhashchange事件,url都會被瀏覽器記錄下來,只能改變#後面的url片段

2、history模式:根據history api中的pushState,replaceState兩個方法。

通過pushstate把頁面的狀態儲存在state物件中,當頁面的url再變回這個url時,可以通過event.state取到這個state物件,從而可以對頁面狀態進行還原,這裡的頁面狀態就是頁面字型顏色,其實滾動條的位置,閱讀進度,元件的開關的這些頁面狀態都可以儲存到state的裡面

<script type="text/javascript">
    window.onhashchange = function
(event){
console.log(event.oldURL, event.newURL); let hash = location.hash.slice(1); document.body.style.color = hash; } window.history.pushState({color:'red'}, 'red', ''); window.onpopstate = function(event){ console.log(event.state); if(event.state && event.state.color === 'red'
){ document.body.style.color = 'red'; } }
</script>