Vue——Vue初始化【三】

来源:https://www.cnblogs.com/wangyang0210/archive/2023/03/12/17207534.html
-Advertisement-
Play Games

前言 今天我們來解密下init.ts中的代碼內容,並結合 vue 生命周期來分析下 vue 的初始化; GitHub github page 內容 init.ts import config from '../config' import { initProxy } from './proxy' i ...


前言

今天我們來解密下init.ts中的代碼內容,並結合 vue 生命周期來分析下 vue 的初始化;

GitHub
github page

內容

lifecycle.png

init.ts

import config from '../config'
import { initProxy } from './proxy'
import { initState } from './state'
import { initRender } from './render'
import { initEvents } from './events'
import { mark, measure } from '../util/perf'
import { initLifecycle, callHook } from './lifecycle'
import { initProvide, initInjections } from './inject'
import { extend, mergeOptions, formatComponentName } from '../util/index'
import type { Component } from 'types/component'
import type { InternalComponentOptions } from 'types/options'
import { EffectScope } from 'v3/reactivity/effectScope'

// vue 實例id
let uid = 0

export function initMixin(Vue: typeof Component) {
  // 接收實例化傳入的參數
  Vue.prototype._init = function (options?: Record<string, any>) {
    //vue 實例
    const vm: Component = this
    // 每個vue實例都有對應的一個實例id
    vm._uid = uid++

    let startTag, endTag
    /* istanbul ignore if */
    // 代碼覆蓋率測試
    if (__DEV__ && config.performance && mark) {
      startTag = `vue-perf-start:${vm._uid}`
      endTag = `vue-perf-end:${vm._uid}`
      mark(startTag)
    }

    // a flag to mark this as a Vue instance without having to do instanceof
    // check
    // 標記作為vue的實例不必去執行instanceof
    vm._isVue = true
    // avoid instances from being observed
    // 避免實例被observed觀察
    vm.__v_skip = true
    // effect scope
    // 影響範圍
    vm._scope = new EffectScope(true /* detached */)
    vm._scope._vm = true
    // merge options
    // 合併參數
    // 判斷是否是子組件
    if (options && options._isComponent) {
      // optimize internal component instantiation
      // 優化內部組件實例化
      // since dynamic options merging is pretty slow, and none of the
      // internal component options needs special treatment.
      // 由於動態選項合併非常緩慢,並且沒有一個內部組件選項需要特殊處理。
      // 傳入vue實例併進行組件初始化
      initInternalComponent(vm, options as any)
    } else {
      // 根組件配置 | 合併參數
      vm.$options = mergeOptions(
        // 解析構造函數參數
        resolveConstructorOptions(vm.constructor as any),
        options || {},
        vm
      )
    }
    /* istanbul ignore else */
    // 代碼覆蓋測試
    if (__DEV__) {
      initProxy(vm)
    } else {
      vm._renderProxy = vm
    }
    // expose real self
    vm._self = vm
    // 核心的核心
    // 初始化生命周期
    initLifecycle(vm)
    // 初始化事件監聽
    initEvents(vm)
    // 初始化渲染
    initRender(vm)
    // 調用生命周期的鉤子函數 | beforeCreate
    callHook(vm, 'beforeCreate', undefined, false /* setContext */)
    // https://v2.cn.vuejs.org/v2/api/#provide-inject
    // 在data/props前進行inject
    initInjections(vm) // resolve injections before data/props
    initState(vm)
    // https://v2.cn.vuejs.org/v2/api/#provide-inject
    // provide 父組件提供的數據
    // inject 子組件進行註入後直接使用
    // 在data/props後進行provide
    initProvide(vm) // resolve provide after data/props
    // 調用生命周期鉤子函數 | created
    callHook(vm, 'created')

    /* istanbul ignore if */
    //   代碼覆蓋測試
    if (__DEV__ && config.performance && mark) {
      vm._name = formatComponentName(vm, false)
      mark(endTag)
      measure(`vue ${vm._name} init`, startTag, endTag)
    }

    // 組件如果設置了el則掛載到指定的el上
    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }
}

/**
 * 初始化內部組件
 *
 * @param vm
 * @param options
 */
export function initInternalComponent(
  vm: Component,
  options: InternalComponentOptions
) {
  const opts = (vm.$options = Object.create((vm.constructor as any).options))
  // doing this because it's faster than dynamic enumeration.
  const parentVnode = options._parentVnode
  opts.parent = options.parent
  opts._parentVnode = parentVnode

  const vnodeComponentOptions = parentVnode.componentOptions!
  opts.propsData = vnodeComponentOptions.propsData
  opts._parentListeners = vnodeComponentOptions.listeners
  opts._renderChildren = vnodeComponentOptions.children
  opts._componentTag = vnodeComponentOptions.tag

  if (options.render) {
    opts.render = options.render
    opts.staticRenderFns = options.staticRenderFns
  }
}

/**
 * 解析構造函數的選項
 *
 * @param Ctor
 * @returns
 */
export function resolveConstructorOptions(Ctor: typeof Component) {
  let options = Ctor.options
  if (Ctor.super) {
    const superOptions = resolveConstructorOptions(Ctor.super)
    const cachedSuperOptions = Ctor.superOptions
    if (superOptions !== cachedSuperOptions) {
      // super option changed,
      // need to resolve new options.
      Ctor.superOptions = superOptions
      // check if there are any late-modified/attached options (#4976)
      const modifiedOptions = resolveModifiedOptions(Ctor)
      // update base extend options
      if (modifiedOptions) {
        extend(Ctor.extendOptions, modifiedOptions)
      }
      options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)
      if (options.name) {
        options.components[options.name] = Ctor
      }
    }
  }
  return options
}

/**
 * 解析修改的選項
 *
 * @param Ctor
 * @returns
 */
function resolveModifiedOptions(
  Ctor: typeof Component
): Record<string, any> | null {
  let modified
  const latest = Ctor.options
  const sealed = Ctor.sealedOptions
  for (const key in latest) {
    if (latest[key] !== sealed[key]) {
      if (!modified) modified = {}
      modified[key] = latest[key]
    }
  }
  return modified
}

Demo 演示

demo 位於example/docs/01.lifecycle.html

通過debugger的方式,能夠更直觀的查看到整個調用的過程;這裡羅列了選項式 api 和組合式 api,後續的 demo 都會以組合式 api 為主。

具體的 debugger 方法可以查看微軟的文檔devtools-guide-chromium,一般來說 F9 進行調試即可;如果你想跳過某一函數,那就 F10;

<script src="../../dist/vue.js"></script>

<div id="app">{{msg}}</div>

<script>
  debugger

  //   Options API || 設置了el
  //   var app = new Vue({
  //     el: '#app',
  //     data: {
  //       msg: 'Hello Vue!'
  //     },
  //     beforeCreate() {
  //       console.log('beforeCreate')
  //     },
  //     created() {
  //       console.log('created')
  //     },
  //     beforeMount() {
  //       console.log('beforeMount')
  //     },
  //     mounted() {
  //       console.log('mounted')
  //     }
  //   })

  // Options API || 手動$mount
  //   new Vue({
  //     data: () => ({
  //       msg: 'helloWord'
  //     }),
  //     beforeCreate: () => {
  //       console.log('beforeCreate')
  //     },
  //     created: () => {
  //       console.log('created')
  //     },
  //     beforeMount: () => {
  //       console.log('beforeMount')
  //     },
  //     mounted: () => {
  //       console.log('mounted')
  //     }
  //   }).$mount('#app')

  // Composition API
  const { ref, beforeCreate, created, beforeMount, mounted } = Vue
  new Vue({
    setup(props) {
      const msg = ref('Hello World!')
      return { msg }
    },
    beforeCreate() {
      console.log('beforeCreate')
    },
    created() {
      console.log('created')
    },
    beforeMount() {
      console.log('beforeMount')
    },
    mounted() {
      console.log('mounted')
    }
  }).$mount('#app')
</script>

內容總結

這裡我們總結下init.ts中大致的內容

  1. 生成 vue 實例 Id;
  2. 標記 vue 實例;
  3. 如果是子組件則傳入 vue 實例和選項並初始化組件,否則則進行選項參數合併,將用戶傳入的選項和構造函數本身的選項進行合併;
  4. 初始化實例生命周期相關屬性,如:$parent、$root、$children、$refs 等;
  5. 初始化組件相關的事件監聽,父級存在監聽事件則掛載到當前實例上;
  6. 初始化渲染,如:$slots、$scopedSlots、$createElement、$attrs、$listeners;
  7. 調用beforeCreate生命周期鉤子函數
  8. 初始化註入數據,在 data/props 之前進行 inject,以允許一個祖先組件向其所有子孫後代註入一個依賴(說白了就是有個傳家寶,爺爺要想傳給孫子,那就要爸爸先 inject,再給兒子)
  9. 初始化狀態,如:props、setup、methods、data(|| observe)、computed、watch
  10. 在 data/props 之後進行 provide
  11. 調用created生命周期鉤子函數,完成初始化
  12. 如果設置了el則自動掛載到對應的元素上,不然就要自己$mount
學無止境,謙卑而行.
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • (索引) 寫在前面 這是《BitBake使用攻略》系列文章的第三篇,主要講解BitBake的基本語法。由於此篇的實驗依賴於第一篇的項目,建議先將HelloWorld項目完成之後再食用此篇為好。 第一篇的鏈接在這:BitBake使用攻略--從HelloWorld講起。 1. BitBake中的任務 對 ...
  • 1. 什麼是Openssl? 在電腦網路上,OpenSSL是一個開放源代碼的軟體庫包,應用程式可以使用這個包來進行安全通信,避免竊聽,同時確認另一端連線者的身份。這個包廣泛被應用在互聯網的網頁伺服器上。 其主要庫是以C語言所寫成,實現了基本的加密功能,實現了SSL與TLS協議。OpenSSL可以運 ...
  • Shell命令-常用操作2 1 vim 用法: vim filename 說明:用於打開指定的文件 三個模式 進入文件後,是normal模式 normal模式:在此模式下可以通過i進入編輯模式,通過:或/進入命令模式; 游標移動:因為linux下不支持游標跟隨滑鼠點擊,所以提供了很多游標快速移動的命 ...
  • 公眾號:MCNU雲原生,文章首發地,歡迎微信搜索關註,更多乾貨,第一時間掌握! @ 一、PostgreSQL是什麼? PostgreSQL是一種開源的關係型資料庫管理系統,也被稱為Postgres。它最初由加拿大電腦科學家Michael Stonebraker在1986年創建,其目標是創建一個具有 ...
  • 前言 我08年畢業,大學跟著老師培訓班學習的C#,那時(2003-2010)它很是時髦,畢業後也就從事了winform窗體應用程式開發。慢慢的web網站興起,就轉到asp.net開發,再到後來就上了另一艘大船(java),前端app混合開發。近三年從事web站點運維,從linux基礎+docker, ...
  • SQL實踐1 藉著學校的資料庫實驗,來對之前學習的SQL語言進行實踐和總結。 實驗環境: macOS 13.2 (22D49) mysql Ver 8.0.32 for macos13.0 on arm64 (Homebrew) DataGrip 2022.3.3 一. DataGrip連接本地My ...
  • 本文已經收錄到Github倉庫,該倉庫包含電腦基礎、Java基礎、多線程、JVM、資料庫、Redis、Spring、Mybatis、SpringMVC、SpringBoot、分散式、微服務、設計模式、架構、校招社招分享等核心知識點,歡迎star~ Github地址:https://github.c ...
  • Redis(REmote DIctionary Service)是一個開源的鍵值對資料庫伺服器。 Redis 更準確的描述是一個數據結構伺服器。Redis 的這種特殊性質讓它在開發人員中很受歡迎。 ...
一周排行
    -Advertisement-
    Play Games
  • 基於.NET Framework 4.8 開發的深度學習模型部署測試平臺,提供了YOLO框架的主流系列模型,包括YOLOv8~v9,以及其系列下的Det、Seg、Pose、Obb、Cls等應用場景,同時支持圖像與視頻檢測。模型部署引擎使用的是OpenVINO™、TensorRT、ONNX runti... ...
  • 十年沉澱,重啟開發之路 十年前,我沉浸在開發的海洋中,每日與代碼為伍,與演算法共舞。那時的我,滿懷激情,對技術的追求近乎狂熱。然而,隨著歲月的流逝,生活的忙碌逐漸占據了我的大部分時間,讓我無暇顧及技術的沉澱與積累。 十年間,我經歷了職業生涯的起伏和變遷。從初出茅廬的菜鳥到逐漸嶄露頭角的開發者,我見證了 ...
  • C# 是一種簡單、現代、面向對象和類型安全的編程語言。.NET 是由 Microsoft 創建的開發平臺,平臺包含了語言規範、工具、運行,支持開發各種應用,如Web、移動、桌面等。.NET框架有多個實現,如.NET Framework、.NET Core(及後續的.NET 5+版本),以及社區版本M... ...
  • 前言 本文介紹瞭如何使用三菱提供的MX Component插件實現對三菱PLC軟元件數據的讀寫,記錄了使用電腦模擬,模擬PLC,直至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1. PLC開發編程環境GX Works2,GX Works2下載鏈接 https:// ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • 1、jQuery介紹 jQuery是什麼 jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之後又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是“write Less,Do More”,即倡導寫更少的代碼,做更多的事情。它封裝 ...
  • 前言 之前的文章把js引擎(aardio封裝庫) 微軟開源的js引擎(ChakraCore))寫好了,這篇文章整點js代碼來測一下bug。測試網站:https://fanyi.youdao.com/index.html#/ 逆向思路 逆向思路可以看有道翻譯js逆向(MD5加密,AES加密)附完整源碼 ...
  • 引言 現代的操作系統(Windows,Linux,Mac OS)等都可以同時打開多個軟體(任務),這些軟體在我們的感知上是同時運行的,例如我們可以一邊瀏覽網頁,一邊聽音樂。而CPU執行代碼同一時間只能執行一條,但即使我們的電腦是單核CPU也可以同時運行多個任務,如下圖所示,這是因為我們的 CPU 的 ...
  • 掌握使用Python進行文本英文統計的基本方法,並瞭解如何進一步優化和擴展這些方法,以應對更複雜的文本分析任務。 ...
  • 背景 Redis多數據源常見的場景: 分區數據處理:當數據量增長時,單個Redis實例可能無法處理所有的數據。通過使用多個Redis數據源,可以將數據分區存儲在不同的實例中,使得數據處理更加高效。 多租戶應用程式:對於多租戶應用程式,每個租戶可以擁有自己的Redis數據源,以確保數據隔離和安全性。 ...