欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

hash和history路由模式區(qū)別示例解析

 更新時間:2023年07月12日 09:51:42   作者:芒果  
這篇文章主要為大家介紹了hash和history路由模式區(qū)別示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

單頁應(yīng)用

目前單頁應(yīng)用(SPA)越來越成為前端主流,單頁應(yīng)用一大特點就是使用前端路由,由前端來直接控制路由跳轉(zhuǎn)邏輯,而不再由后端人員控制,這給了前端更多的自由。

目前前端路由主要有兩種實現(xiàn)方式:hash模式和history模式,下面分別詳細說明。

hash模式

這個我們應(yīng)該不陌生,比如在用超鏈接制作錨點跳轉(zhuǎn)的時候,就會發(fā)現(xiàn),url后面跟了"#id",hash值就是url中從"#"號開始到結(jié)束的部分

hash值變化瀏覽器不會重新發(fā)起請求,但是會觸發(fā)window.hashChange事件,假如我們在hashChange事件中獲取當(dāng)前的hash值,并根據(jù)hash值來修改頁面內(nèi)容,則達到了前端路由的目的。

html:菜單中href設(shè)置為hash形式,id為app中放置頁面內(nèi)容

<ul id="menu">
    <li>
        <a href="#index" rel="external nofollow" >首頁</a>
    </li>
    <li>
        <a href="#news" rel="external nofollow" >資訊</a>
    </li>
    <li>
        <a href="#user" rel="external nofollow" >個人中心</a>
    </li>
</ul>

<div id="app"></div>

js:在window.onhashchange中獲取hash值,根據(jù)不同的值,修改app中不同的內(nèi)容,起到了路由的效果

function hashChange(e){
    // console.log(location.hash)
    // console.log(location.href)
    //
    // console.log(e.newURL)
    // console.log(e.oldURL)
    let app = document.getElementById('app')
    switch (location.hash) {
        case '#index':
            app.innerHTML = '<h1>這是首頁內(nèi)容</h1>'
            break
        case '#news':
            app.innerHTML = '<h1>這是新聞內(nèi)容</h1>'
            break
        case '#user':
            app.innerHTML = '<h1>這是個人中心內(nèi)容</h1>'
            break
        default:
            app.innerHTML = '<h1>404</h1>'
    }
}

window.onhashchange = hashChange

hashChange()

上面這個實現(xiàn)方式比較簡陋,我們可以再封裝一下

class Router {
constructor(){
    this.routers = []  //存放我們的路由配置
}
add(route,callback){
    this.routers.push({
        path:route,
        render:callback
    })
}
listen(callback){
    window.onhashchange = this.hashChange(callback)
    this.hashChange(callback)()  //首次進入頁面的時候沒有觸發(fā)hashchange,必須要就單獨調(diào)用一下
}
hashChange(callback){
    let self = this
    return function () {
        let hash = location.hash
        console.log(hash)
        for(let i=0;i<self.routers.length;i++){
            let route = self.routers[i]
            if(hash===route.path){
                callback(route.render())
                return
            }
        }
    }
}
}
let router = new Router()
router.add('#index',()=>{
return '<h1>這是首頁內(nèi)容</h1>'
})
router.add('#news',()=>{
return ?'<h1>這是新聞內(nèi)容</h1>'
})
router.add('#user',()=>{
return ?'<h1>這是個人中心內(nèi)容</h1>'
})
router.listen((renderHtml)=>{
let app = document.getElementById('app')
app.innerHTML = renderHtml
})

實現(xiàn)一個Router類,通過add方法添加路由配置,第一個參數(shù)為路由路徑,第二個參數(shù)為render函數(shù),返回要插入頁面的html;通過listen方法,監(jiān)聽hash變化,并將每個路由返回的html,插入到app中。

這樣我們就實現(xiàn)了一個簡單的hash路由。

history模式

hash模式看起來是比較丑的,都帶個"#"號,我們也可以采取history模式,history就是我們平時看到的正常的連接形式

https://www.baidu.com#plan/index //hash模式路由
https://www.baidu.com/plan/index //history模式路由

history模式基于window.history對象的方法

在HTML4中,已經(jīng)支持window.history對象來控制頁面歷史記錄跳轉(zhuǎn),常用的方法包括:

history.forward(); //在歷史記錄中前進一步

history.back(); //在歷史記錄中后退一步

history.go(n): //在歷史記錄中跳轉(zhuǎn)n步驟,n=0為刷新本頁,n=-1為后退一頁。

在HTML5中,window.history對象得到了擴展,新增的API包括:

history.pushState(data,title);//向歷史記錄中追加一條記錄

history.replaceState(data,title);//替換當(dāng)前頁在歷史記錄中的信息。

history.state;//是一個屬性,可以得到當(dāng)前頁的state信息。

window.onpopstate;//是一個事件,在點擊瀏覽器后退按鈕或js調(diào)用forward()、back()、go()時觸發(fā)。監(jiān)聽函數(shù)中可傳入一個event對象,event.state即為通過pushState()或replaceState()方法傳入的data參數(shù)

history模式原理可以這樣理解,首先我們要改造我們的超鏈接,給每個超鏈接增加onclick方法,阻止默認的超鏈接跳轉(zhuǎn),改用history.pushState或history.replaceState來更改瀏覽器中的url,并修改頁面內(nèi)容。由于通過history的api調(diào)整,并不會向后端發(fā)起請求,所以也就達到了前端路由的目的。

如果用戶使用瀏覽器的前進后退按鈕,則會觸發(fā)window.onpopstate事件,監(jiān)聽頁面根據(jù)路由地址修改頁面內(nèi)容。

也不一定非要用超鏈接,任意元素作為菜單都行,只要在點擊事件中通過history進行調(diào)整即可。

html:

<ul id="menu">
<li>
    <a href="/index" rel="external nofollow" >首頁</a>
</li>
<li>
    <a href="/news" rel="external nofollow" >資訊</a>
</li>
<li>
    <a href="/user" rel="external nofollow" >個人中心</a>
</li>
</ul>
<div id="app"></div>

js:

//改造超鏈接,阻止默認跳轉(zhuǎn),默認的跳轉(zhuǎn)是會刷新頁面的
document.querySelector('#menu').addEventListener('click',function (e) {
if(e.target.nodeName ==='A'){
    e.preventDefault()
    let path = e.target.getAttribute('href')  //獲取超鏈接的href,改為pushState跳轉(zhuǎn),不刷新頁面
    window.history.pushState({},'',path)  //修改瀏覽器中顯示的url地址
    render(path)  //根據(jù)path,更改頁面內(nèi)容
}
})
function render(path) {
let app = document.getElementById('app')
switch (path) {
    case '/index':
        app.innerHTML = '<h1>這是首頁內(nèi)容</h1>'
        break
    case '/news':
        app.innerHTML = '<h1>這是新聞內(nèi)容</h1>'
        break
    case '/user':
        app.innerHTML = '<h1>這是個人中心內(nèi)容</h1>'
        break
    default:
        app.innerHTML = '<h1>404</h1>'
}
}
//監(jiān)聽瀏覽器前進后退事件,并根據(jù)當(dāng)前路徑渲染頁面
window.onpopstate = function (e) {
    render(location.pathname)
}
//第一次進入頁面顯示首頁
render('/index')
上面這個寫法太low,我們可以用類封裝一下,通過add方法添加路由,通過pushState進行跳轉(zhuǎn),初始化時更改所以超鏈接的跳轉(zhuǎn)方式
class Router {
    constructor(){
    this.routers = []
    this.renderCallback = null
}
add(route,callback){
    this.routers.push({
        path:route,
        render:callback
    })
}
pushState(path,data={}){
    window.history.pushState(data,'',path)
    this.renderHtml(path)
}
listen(callback){
    this.renderCallback = callback
    this.changeA()
    window.onpopstate = ()=>this.renderHtml(this.getCurrentPath())
    this.renderHtml(this.getCurrentPath())
}
changeA(){
    document.addEventListener('click', (e)=> {
        if(e.target.nodeName==='A'){
            e.preventDefault()
            let path = e.target.getAttribute('href')
            this.pushState(path)
        }
    })
}
getCurrentPath(){
    return location.pathname
}
renderHtml(path){
    for(let i=0;i<this.routers.length;i++){
        let route = this.routers[i]
        if(path===route.path){
            this.renderCallback(route.render())
            return
        }
    }
}
}
let router = new Router()
router.add('/index',()=>{
return '<h1>這是首頁內(nèi)容</h1>'
})
router.add('/news',()=>{
return  '<h1>這是新聞內(nèi)容</h1>'
})
router.add('/user',()=>{
return  '<h1>這是個人中心內(nèi)容</h1>'
})
router.listen((renderHtml)=>{
let app = document.getElementById('app')
app.innerHTML = renderHtml
})

當(dāng)然,上面這個實現(xiàn)只是一個非常初級的demo,并不能用于真正的開發(fā)場景,只是加深對前端路由的理解。

hash模式和history模式的區(qū)別

hash模式較丑,history模式較優(yōu)雅

pushState設(shè)置的新URL可以是與當(dāng)前URL同源的任意URL;而hash只可修改#后面的部分,故只可設(shè)置與當(dāng)前同文檔的URL

pushState設(shè)置的新URL可以與當(dāng)前URL一模一樣,這樣也會把記錄添加到棧中;而hash設(shè)置的新值必須與原來不一樣才會觸發(fā)記錄添加到棧中

pushState通過stateObject可以添加任意類型的數(shù)據(jù)到記錄中;而hash只可添加短字符串

pushState可額外設(shè)置title屬性供后續(xù)使用

hash兼容IE8以上,history兼容IE10以上

history模式需要后端配合將所有訪問都指向index.html,否則用戶刷新頁面,會導(dǎo)致404錯誤

以上就是hash和history路由模式區(qū)別示例解析的詳細內(nèi)容,更多關(guān)于hash history路由模式區(qū)別的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論