日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

VueRouter源码详细解读

發布時間:2024/8/1 vue 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 VueRouter源码详细解读 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

路由模式

1. hash

使用 URL hash 值來作路由。支持所有瀏覽器,包括不支持 HTML5 History Api 的瀏覽器。
Hash URL,當 # 后面的哈希值發生變化時,不會向服務器請求數據,可以通過 hashchange 事件來監聽到 URL 的變化,從而進行跳轉頁面。

2. history

依賴 HTML5 History API 和服務器配置

3. abstract

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

router調用

import Vue from 'vue' import VueRouter from 'vue-router' import Home from '@/views/Home.vue' import Demo from '@/views/Demo.vue' import InstantMessager from '@/views/InstantMessager' import Seller from '@/views/Seller' Vue.use(VueRouter)const routes = [{path: '/',name: 'Home',component: Home},{path: '/demo',name: 'Demo',component: Demo,meta: {isFullPage: true}},{path: '/instantMessager',name: 'InstantMessager',component: InstantMessager,},{path: '/seller',name: 'Seller',component: Seller,meta: {isFullPage: true}}, ] const router = new VueRouter({mode: '',base: process.env.BASE_URL,routes })export default router

源碼解析

1. Install

Vue.use(VueRouter)會執行install方法
1、在beforeCreated中初始化vue-router,并將_route響應式
2、在 Vue 原型上添加 r o u t e r 屬 性 ( V u e R o u t e r ) 并 代 理 到 t h i s . router 屬性( VueRouter )并代理到 this.router屬性(VueRouter)并代理到this.root._router
3、Vue上注冊router-link和router-view兩個組件

export function install (Vue) {if (install.installed && _Vue === Vue) returninstall.installed = true_Vue = Vueconst isDef = v => v !== undefinedconst registerInstance = (vm, callVal) => {let i = vm.$options._parentVnodeif (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {i(vm, callVal)}}Vue.mixin({beforeCreate () {if (isDef(this.$options.router)) {this._routerRoot = thisthis._router = this.$options.routerthis._router.init(this)Vue.util.defineReactive(this, '_route', this._router.history.current)} else {this._routerRoot = (this.$parent && this.$parent._routerRoot) || this}registerInstance(this, this)},destroyed () {registerInstance(this)}})Object.defineProperty(Vue.prototype, '$router', {get () { return this._routerRoot._router }})Object.defineProperty(Vue.prototype, '$route', {get () { return this._routerRoot._route }})Vue.component('RouterView', View)Vue.component('RouterLink', Link)const strats = Vue.config.optionMergeStrategies// use the same hook merging strategy for route hooksstrats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created }

2. router實例

生成實例過程中,主要做了以下兩件事
1、根據配置數組(傳入的routes)生成路由配置記錄表。
2、根據不同模式生成監控路由變化的History對象

首先我們看到在new VueRouter()的時候傳入的參數,比如mode,base,routes等。mode是導航模式,有hash(默認),history,abstract。
hash 是默認值,如果不傳入或者瀏覽器不支持history時,就用hash。

class VueRouter {constructor (options: RouterOptions = {}) {this.app = nullthis.apps = []this.options = optionsthis.beforeHooks = []this.resolveHooks = []this.afterHooks = []this.matcher = createMatcher(options.routes || [], this)let mode = options.mode || 'hash'this.fallback =mode === 'history' && !supportsPushState && options.fallback !== falseif (this.fallback) {mode = 'hash'}if (!inBrowser) {mode = 'abstract'}this.mode = modeswitch (mode) {case 'history':this.history = new HTML5History(this, options.base)breakcase 'hash':this.history = new HashHistory(this, options.base, this.fallback)breakcase 'abstract':this.history = new AbstractHistory(this, options.base)breakdefault:if (process.env.NODE_ENV !== 'production') {assert(false, `invalid mode: ${mode}`)}}}

1). createMatcher
根據routes數組,做一個映射,返回match、addRoutes 、addRoute、getRoutes 方法。

this.matcher = createMatcher(options.routes || [], this)// 方法createMatcher: export function createMatcher (routes: Array<RouteConfig>,router: VueRouter ): Matcher {const { pathList, pathMap, nameMap } = createRouteMap(routes)function addRoutes (routes) { }function addRoute (parentOrRoute, route) {}function getRoutes () { }function match { }return {match,addRoute,getRoutes,addRoutes} }

2)createRouteMap, 創建路由映射表, 路徑/名稱的映射表,生成路由記錄(route records);

const { pathList, pathMap, nameMap } = createRouteMap(routes)

路由記錄屬性如下:

const record: RouteRecord = {path: normalizedPath,regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),components: route.components || { default: route.component },alias: route.alias? typeof route.alias === 'string'? [route.alias]: route.alias: [],instances: {},enteredCbs: {},name,parent,matchAs,redirect: route.redirect,beforeEnter: route.beforeEnter,meta: route.meta || {},props:route.props == null? {}: route.components? route.props: { default: route.props }}

如某一條路由記錄

createRouteMap為每條路由生成路由記錄,結果如下:

2)判斷mode的值,根據不同的mode走不同的方法,
若瀏覽器不支持HTML5History方式(通過supportsPushState變量判斷),則mode強制設為’hash’;若不是在瀏覽器環境下運行,則mode強制設為’abstract’

點擊跳轉主線:

this.$router.push(’/demo’) ->History.push -> transitionTo -> match -> createRoute -> confirmTransition -> updateRoute-> render

createRoute

總結

以上是生活随笔為你收集整理的VueRouter源码详细解读的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。