站長資訊網
        最全最豐富的資訊網站

        vue-roter有幾種模式

        vue-roter有3種模式:1、hash模式,用URL hash值來做路由,支持所有瀏覽器;該模式實現的路由,在通過鏈接后面添加““#”+路由名字”。2、history模式,由h5提供的history對象實現,依賴H5 History API和服務器配置。3、abstract模式,支持所有JS運行環境,如Node服務器端,如果發現沒有瀏覽器的API,路由會自動強制進入該模式。

        vue-roter有幾種模式

        本教程操作環境:windows7系統、vue3版,DELL G3電腦。

        Vue-router 是vue框架的路由插件。

        vue-roter有幾種模式

        vue-roter有幾種模式

        根據vue-router官網,我們可以明確看到vue-router的mode值有3種

        • hash

        • history

        • abstract

        其中,hash 和 history 是 SPA 單頁應用程序的基礎。

        先說結論: spa應用路由有2種模式,hash 和 history,vue路由有3種模式,比 spa 多了一個 abstract。

        源碼分析

        在vue-router中通過mode這個參數修改路由的模式:

        const router = new VueRouter({   mode: 'history',   routes: [...] })

        具體怎么實現的呢,首先我們下載 vue-router 的源碼

        抽離出來對mode的處理

        class vueRouter {     constructor(options) {         let mode = options.mode || 'hash'         this.fallback =         mode === 'history' && !supportsPushState && options.fallback !== false         if (this.fallback) {             mode = 'hash'         }         if (!inBrowser) {             mode = 'abstract'         }         this.mode = mode          switch (mode) {             case 'history':                 this.history = new HTML5History(this, options.base)                 break             case 'hash':                 this.history = new HashHistory(this, options.base, this.fallback)                 break             case 'abstract':                 this.history = new AbstractHistory(this, options.base)                 break             default:                 if (process.env.NODE_ENV !== 'production') {                     assert(false, `invalid mode: ${mode}`)                 }         }     } }

        可以看到默認使用的是 hash 模式,當設置為 history 時,如果不支持 history 方法,也會強制使用 hash 模式。 當不在瀏覽器環境,比如 node 中時,直接強制使用 abstract 模式。

        hash模式

        閱讀這部分源碼前,我們先來了解下 hash 的基礎: 根據MDN上的介紹,Location 接口的 hash 屬性返回一個 USVString,其中會包含URL標識中的 '#' 和 后面URL片段標識符,'#' 和后面URL片段標識符被稱為 hash。 它有這樣一些特點:

        • 在第一個#后面出現的任何字符,都會被瀏覽器解讀為位置標識符。這意味著,這些字符都不會被發送到服務器端。

        • 單單改變#后的部分,瀏覽器只會滾動到相應位置,不會重新加載網頁。

        • 每一次改變#后的部分,都會在瀏覽器的訪問歷史中增加一個記錄,使用"后退"按鈕,就可以回到上一個位置。

        • 可通過window.location.hash屬性讀取 hash 值,并且 window.location.hash 這個屬性可讀可寫。

        • 使用 window.addEventListener("hashchange", fun) 可以監聽 hash 的變化

        了解了這些基本知識后,我們繼續來看 vue-router 源碼對 /src/history/hash.js 的處理

            const handleRoutingEvent = () => {       const current = this.current       if (!ensureSlash()) {         return       }       this.transitionTo(getHash(), route => {         if (supportsScroll) {           handleScroll(this.router, route, current, true)         }         if (!supportsPushState) {           replaceHash(route.fullPath)         }       })     }     const eventType = supportsPushState ? 'popstate' : 'hashchange'     window.addEventListener(       eventType,       handleRoutingEvent     )     this.listeners.push(() => {       window.removeEventListener(eventType, handleRoutingEvent)     })

        首先也是使用 window.addEventListener("hashchange", fun) 監聽路由的變化,然后使用 transitionTo 方法更新視圖

          push (location: RawLocation, onComplete?: Function, onAbort?: Function) {     const { current: fromRoute } = this     this.transitionTo(       location,       route => {         pushHash(route.fullPath)         handleScroll(this.router, route, fromRoute, false)         onComplete && onComplete(route)       },       onAbort     )   }    replace (location: RawLocation, onComplete?: Function, onAbort?: Function) {     const { current: fromRoute } = this     this.transitionTo(       location,       route => {         replaceHash(route.fullPath)         handleScroll(this.router, route, fromRoute, false)         onComplete && onComplete(route)       },       onAbort     )   }

        vue-router 的2個主要API push 和 replace 也是簡單處理了下 hash , 然后調用 transitionTo 方法更新視圖

        history模式

        老規矩,先來了解下 HTML5History 的的基本知識: 根據MDN上的介紹,History 接口允許操作瀏覽器的曾經在標簽頁或者框架里訪問的會話歷史記錄。 使用 back(), forward()和 go() 方法來完成在用戶歷史記錄中向后和向前的跳轉。 HTML5引入了 history.pushState() 和 history.replaceState() 方法,它們分別可以添加和修改歷史記錄條目。 稍微了解下 history.pushState():

        window.onpopstate = function(e) {    alert(2); }  let stateObj = {     foo: "bar", };  history.pushState(stateObj, "page 2", "bar.html");

        這將使瀏覽器地址欄顯示為 mozilla.org/bar.html ,但并不會導致瀏覽器加載 bar.html ,甚至不會檢查bar.html 是否存在。 也就是說,雖然瀏覽器 URL 改變了,但不會立即重新向服務端發送請求,這也是 spa應用 更新視圖但不 重新請求頁面的基礎。 接著我們繼續看 vue-router 源碼對 /src/history/html5.js 的處理:

            const handleRoutingEvent = () => {       const current = this.current        // Avoiding first `popstate` event dispatched in some browsers but first       // history route not updated since async guard at the same time.       const location = getLocation(this.base)       if (this.current === START && location === this._startLocation) {         return       }        this.transitionTo(location, route => {         if (supportsScroll) {           handleScroll(router, route, current, true)         }       })     }     window.addEventListener('popstate', handleRoutingEvent)     this.listeners.push(() => {       window.removeEventListener('popstate', handleRoutingEvent)     })

        處理邏輯和 hash 相似,使用 window.addEventListener("popstate", fun) 監聽路由的變化,然后使用 transitionTo 方法更新視圖。 push 和 replace 等方法就不再詳細介紹。

        abstract模式

        最后我們直接來看一下對 /src/history/abstract.js 的處理:

          constructor (router: Router, base: ?string) {     super(router, base)     this.stack = []     this.index = -1   }

        首先定義了2個變量,stack 來記錄調用的記錄, index 記錄當前的指針位置

          push (location: RawLocation, onComplete?: Function, onAbort?: Function) {     this.transitionTo(       location,       route => {         this.stack = this.stack.slice(0, this.index + 1).concat(route)         this.index++         onComplete && onComplete(route)       },       onAbort     )   }    replace (location: RawLocation, onComplete?: Function, onAbort?: Function) {     this.transitionTo(       location,       route => {         this.stack = this.stack.slice(0, this.index).concat(route)         onComplete && onComplete(route)       },       onAbort     )   }

        push 和 replac方法 也是通過 stack 和 index 2個變量,模擬出瀏覽器的歷史調用記錄。

        總結

        終于到了最后的總結階段了:

        • hash 和 history 的使用方式差不多,hash 中路由帶 # ,但是使用簡單,不需要服務端配合,站在技術角度講,這個是配置最簡單的模式,本人感覺這也是 hash 被設為默認模式的原因

        • history 模式需要服務端配合處理404的情況,但是路由中不帶 # ,比 hash 美觀一點。

        • abstract 模式支持所有JavaScript運行環境,如Node.js服務器端,如果發現沒有瀏覽器的API,路由會自動強制進入這個模式。

          abstract 模式沒有使用瀏覽器api,可以放到node環境或者桌面應用中,是對 spa應用 的兜底和能力擴展。

        【相關視頻教程推薦:vue視頻教程、web前端入門】

        贊(0)
        分享到: 更多 (0)
        網站地圖   滬ICP備18035694號-2    滬公網安備31011702889846號
        主站蜘蛛池模板: 欧美亚洲综合免费精品高清在线观看| 一本一本久久A久久综合精品| 狠狠精品久久久无码中文字幕| 久久精品天天中文字幕人妻| 久久精品国产一区二区三区不卡 | 欧美精品区一级片免费播放| 午夜影视日本亚洲欧洲精品一区| 欧洲精品久久久av无码电影| 蜜臀精品国产高清在线观看| 国产A√精品区二区三区四区| 国产精品合集一区二区三区 | 99久久精品国产综合一区 | 精品国产毛片一区二区无码| 久久久91精品国产一区二区三区| 精品少妇无码AV无码专区| 午夜精品久久久久久影视777| 国产免费久久精品99久久| 99国产精品国产免费观看| 久久精品这里热有精品| 精品国内片67194| 91国在线啪精品一区| 精品卡一卡二卡乱码高清| 精品亚洲成a人片在线观看少妇| 无码人妻精品一区二区三区夜夜嗨| 亚洲精品第一国产综合精品99| 人妻少妇精品久久| 欧美国产成人精品一区二区三区 | 国产精品久久久久一区二区三区| 亚洲国产精品成| 999精品色在线播放| 国产A∨国片精品一区二区| 2021年精品国产福利在线| 四虎影视国产精品永久在线| 日韩欧国产精品一区综合无码| 亚洲精品小视频| 99久久综合国产精品二区| 91精品国产品国语在线不卡 | 99RE8这里有精品热视频| 国产999精品久久久久久| 粉嫩精品美女国产在线观看| 国产成人精品久久亚洲|