hash模式
hash模式主要通过监听URL地址的哈希值的变化来实现页面更新文章来源地址https://www.toymoban.com/news/detail-719973.html
function routeHandle() {
let appElm = document.querySelector('#app')
let hash = window.location.hash.slice(1)
switch (hash) {
case '':
case '/':
case '/home':
appElm.innerHTML = `
<h1>Home</h1>
<button id="toListBtn">to list</button>
`
bindEvent()
break
case '/list':
appElm.innerHTML = `
<h1>List</h1>
<button id="toHomeBtn">to home</button>
`
bindEvent()
break
default:
appElm.innerHTML = `
<h1>404</h1>
`
break
}
}
window.addEventListener('hashchange', routeHandle, false)
完整代码
<body>
<div id="app"></div>
</body>
function routeHandle() {
let appElm = document.querySelector('#app')
let hash = window.location.hash.slice(1)
switch (hash) {
case '':
case '/':
case '/home':
appElm.innerHTML = `
<h1>Home</h1>
<button id="toListBtn">to list</button>
`
bindEvent()
break
case '/list':
appElm.innerHTML = `
<h1>List</h1>
<button id="toHomeBtn">to home</button>
`
bindEvent()
break
default:
appElm.innerHTML = `
<h1>404</h1>
`
break
}
}
function toListBtnHandle() {
window.location.hash = '#/list'
}
function toHomeBtnHandle() {
window.location.hash = '#/'
}
function bindEvent() {
let toListBtnElm = document.querySelector('#toListBtn')
let toHomeBtnElm = document.querySelector('#toHomeBtn')
toListBtnElm && toListBtnElm.addEventListener('click', toListBtnHandle, false)
toHomeBtnElm && toHomeBtnElm.addEventListener('click', toHomeBtnHandle, false)
}
window.addEventListener('hashchange', routeHandle, false)
;(() => {
routeHandle()
})()
文章来源:https://www.toymoban.com/news/detail-719973.html
到了这里,关于单页面路由跳转之hash模式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!