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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > vue >内容正文

vue

Vue2 源码漫游(一)

發(fā)布時間:2023/12/10 vue 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Vue2 源码漫游(一) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Vue2 源碼漫游(一)

描述:

Vue框架中的基本原理可能大家都基本了解了,但是還沒有漫游一下源碼。 所以,覺得還是有必要跑一下。 由于是代碼漫游,所以大部分為關(guān)鍵性代碼,以主線路和主要分支的代碼為主,大部分理解都寫在代碼注釋中。

一、代碼主線

文件結(jié)構(gòu)1-->4,代碼執(zhí)行順序4-->1

1.platforms/web/entry-runtime.js/index.js

web不同平臺入口;

/* @flow */import Vue from './runtime/index'export default Vue

2.runtime/index.js

為Vue配置一些屬性方法

/* @flow */import Vue from 'core/index' import config from 'core/config' import { extend, noop } from 'shared/util' import { mountComponent } from 'core/instance/lifecycle' import { devtools, inBrowser, isChrome } from 'core/util/index'import {query,mustUseProp,isReservedTag,isReservedAttr,getTagNamespace,isUnknownElement } from 'web/util/index'import { patch } from './patch' import platformDirectives from './directives/index' import platformComponents from './components/index'// install platform specific utils Vue.config.mustUseProp = mustUseProp Vue.config.isReservedTag = isReservedTag Vue.config.isReservedAttr = isReservedAttr Vue.config.getTagNamespace = getTagNamespace Vue.config.isUnknownElement = isUnknownElement// install platform runtime directives & components extend(Vue.options.directives, platformDirectives) extend(Vue.options.components, platformComponents)// install platform patch function Vue.prototype.__patch__ = inBrowser ? patch : noop// public mount method Vue.prototype.$mount = function (el?: string | Element,hydrating?: boolean ): Component {el = el && inBrowser ? query(el) : undefinedreturn mountComponent(this, el, hydrating) }// devtools global hook /* istanbul ignore next */ Vue.nextTick(() => {if (config.devtools) {if (devtools) {devtools.emit('init', Vue)} else if (process.env.NODE_ENV !== 'production' && isChrome) {console[console.info ? 'info' : 'log']('Download the Vue Devtools extension for a better development experience:\n' +'https://github.com/vuejs/vue-devtools')}}if (process.env.NODE_ENV !== 'production' &&config.productionTip !== false &&inBrowser && typeof console !== 'undefined') {console[console.info ? 'info' : 'log'](`You are running Vue in development mode.\n` +`Make sure to turn on production mode when deploying for production.\n` +`See more tips at https://vuejs.org/guide/deployment.html`)} }, 0)export default Vue

3.core/index.js

/* @flow */import config from '../config' import { initUse } from './use' import { initMixin } from './mixin' import { initExtend } from './extend' import { initAssetRegisters } from './assets' import { set, del } from '../observer/index' import { ASSET_TYPES } from 'shared/constants' import builtInComponents from '../components/index'import {warn,extend,nextTick,mergeOptions,defineReactive } from '../util/index'export function initGlobalAPI (Vue: GlobalAPI) {// 重寫config,創(chuàng)建了一個configDef對象,最終目的是為了Object.defineProperty(Vue, 'config', configDef)const configDef = {}configDef.get = () => configif (process.env.NODE_ENV !== 'production') {configDef.set = () => {warn('Do not replace the Vue.config object, set individual fields instead.')}}Object.defineProperty(Vue, 'config', configDef)// 具體Vue.congfig的具體內(nèi)容就要看../config文件了// exposed util methods.// NOTE: these are not considered part of the public API - avoid relying on them unless you are aware of the risk.// 添加一些方法,但是該方法并不是公共API的一部分。源碼中引入了flow.jsVue.util = {warn, // 查看'../util/debug'extend,//查看'../sharde/util'mergeOptions,//查看'../util/options'defineReactive//查看'../observe/index'}Vue.set = set //查看'../observe/index' Vue.delete = del//查看'../observe/index'Vue.nextTick = nextTick//查看'../util/next-click'.在callbacks中注冊回調(diào)函數(shù)// 創(chuàng)建一個純凈的options對象,添加components、directives、filters屬性Vue.options = Object.create(null)ASSET_TYPES.forEach(type => {Vue.options[type + 's'] = Object.create(null)})// this is used to identify the "base" constructor to extend all plain-object// components with in Weex's multi-instance scenarios.Vue.options._base = Vue// ../components/keep-alive.js 拷貝組件對象。該部分最重要的一部分。extend(Vue.options.components, builtInComponents)// Vue.options = {// components : {// KeepAlive : {// name : 'keep-alive',// abstract : true,// created : function created(){},// destoryed : function destoryed(){},// props : {// exclude : [String, RegExp, Array],// includen : [String, RegExp, Array],// max : [String, Number]// },// render : function render(){},// watch : {// exclude : function exclude(){},// includen : function includen(){},// }// },// directives : {},// filters : {},// _base : Vue// }// }// 添加Vue.use方法,使用插件,內(nèi)部維護一個插件列表_installedPlugins,如果插件有install方法就執(zhí)行自己的install方法,否則如果plugin是一個function就執(zhí)行這個方法,傳參(this, args)initUse(Vue)// ./mixin.js 添加Vue.mixin方法,this.options = mergeOptions(this.options, mixin),initMixin(Vue)// ./extend.js 添加Vue.cid(每一個夠著函數(shù)實例都有一個cid,方便緩存),Vue.extend(options)方法initExtend(Vue)// ./assets.js 創(chuàng)建收集方法Vue[type] = function (id: string, definition: Function | Object),其中type : component / directive / filterinitAssetRegisters(Vue) }

Vue.util對象的部分解釋:

  • Vue.util.warn
    warn(msg, vm) 警告方法代碼在util/debug.js,
    通過var trac = generateComponentTrace(vm)方法vm=vm.$parent遞歸收集到msg出處。
    然后判斷是否存在console對象,如果有 console.error([Vue warn]: ${msg}${trace})。
    如果config.warnHandle存在config.warnHandler.call(null, msg, vm, trace)

  • Vue.util.extend

    extend (to: Object, _from: ?Object):Object Object類型淺拷貝方法代碼在shared/util.js
  • Vue.util.mergeOptions

    合并,vue實例化和實現(xiàn)繼承的核心方法,代碼在shared/options.jsmergeOptions (parent: Object,child: Object,vm?: Component) 先通過normalizeProps、normalizeInject、normalizeDirectives以O(shè)bject-base標(biāo)準(zhǔn)化,然后依據(jù)strats合并策略進行合并。strats是對data、props、watch、methods等實例化參數(shù)的合并策略。除此之外還有defaultStrat默認策略。后期暴露的mixin和Vue.extend()就是從這里出來的。[官網(wǎng)解釋][1]
  • Vue.util.defineReactive

    大家都知道的數(shù)據(jù)劫持核心方法,代碼在shared/util.jsdefineReactive (obj: Object,key: string,val: any,customSetter?: ?Function,shallow?: boolean)

4.instance/index.js Vue對象生成文件

import { initMixin } from './init' import { stateMixin } from './state' import { renderMixin } from './render' import { eventsMixin } from './events' import { lifecycleMixin } from './lifecycle' import { warn } from '../util/index'function Vue (options) {// 判斷是否是new調(diào)用。if (process.env.NODE_ENV !== 'production' &&!(this instanceof Vue)) {warn('Vue is a constructor and should be called with the `new` keyword')}// 開始初始化this._init(options) } // 添加Vue._init(options)內(nèi)部方法,./init.js initMixin(Vue) /*** ./state.js* 添加屬性和方法* Vue.prototype.$data * Vue.prototype.$props* Vue.prototype.$watch* Vue.prototype.$set* Vue.prototype.$delete*/ stateMixin(Vue) /*** ./event.js* 添加實例事件* Vue.prototype.$on* Vue.prototype.$once* Vue.prototype.$off* Vue.prototype.$emit*/ eventsMixin(Vue) /*** ./lifecycle.js* 添加實例生命周期方法* Vue.prototype._update* Vue.prototype.$forceUpdate* Vue.prototype.$destroy*/ lifecycleMixin(Vue) /*** ./render.js* 添加實例渲染方法* 通過執(zhí)行installRenderHelpers(Vue.prototype);為實例添加很多helper* Vue.prototype.$nextTick* Vue.prototype._render*/ renderMixin(Vue)export default Vue

5.instance/init.js

初始化,完成主組件的所有動作的主線。從這兒出發(fā)可以理清observer、watcher、compiler 、render等

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'let uid = 0export function initMixin (Vue: Class<Component>) {Vue.prototype._init = function (options?: Object) {const vm: Component = this// a uidvm._uid = uid++let startTag, endTag/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {startTag = `vue-perf-start:${vm._uid}`endTag = `vue-perf-end:${vm._uid}`mark(startTag)}// a flag to avoid this being observedvm._isVue = true// merge optionsif (options && options._isComponent) {// optimize internal component instantiation// since dynamic options merging is pretty slow, and none of the// internal component options needs special treatment.initInternalComponent(vm, options)} else {vm.$options = mergeOptions(resolveConstructorOptions(vm.constructor),options || {},vm)}/* istanbul ignore else */if (process.env.NODE_ENV !== 'production') {initProxy(vm)} else {vm._renderProxy = vm}// expose real selfvm._self = vminitLifecycle(vm)initEvents(vm)/*** 添加vm.$createElement vm.$vnode vm.$slots vm.* 創(chuàng)建vm.$attrs / vm.$listeners 并且轉(zhuǎn)換為getter和setter* */initRender(vm)callHook(vm, 'beforeCreate')initInjections(vm) // resolve injections before data/props vm.$scopedSlots /*** 1、創(chuàng)建 vm._watchers = [];* 2、執(zhí)行if (opts.props) { initProps(vm, opts.props); } 驗證props后調(diào)用defineReactive轉(zhuǎn)化,并且代理數(shù)據(jù)proxy(vm, "_props", key);* 3、執(zhí)行if (opts.methods) { initMethods(vm, opts.methods); } 然后vm[key] = methods[key] == null ? noop : bind(methods[key], vm);* 4、處理data,* if (opts.data) {* initData(vm);* } else {* observe(vm._data = {}, true /* asRootData */);* }* 5、執(zhí)行initData:* (1)先判斷data的屬性是否有與methods和props值同名* (2)獲取vm.data(如果為function,執(zhí)行g(shù)etData(data, vm)),代理proxy(vm, "_data", key);* (3)執(zhí)行 observe(data, true /* asRootData */);遞歸觀察* 6、完成observe,具體看解釋*/initState(vm)initProvide(vm) // resolve provide after data/propscallHook(vm, 'created')/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {vm._name = formatComponentName(vm, false)mark(endTag)measure(`vue ${vm._name} init`, startTag, endTag)}if (vm.$options.el) {vm.$mount(vm.$options.el)}} }

二、observe 響應(yīng)式數(shù)據(jù)轉(zhuǎn)換

1.前置方法 observe(value, asRootData)

function observe (value, asRootData) {// 如果value不是是Object 或者是VNode這不用轉(zhuǎn)換if (!isObject(value) || value instanceof VNode) {return}var ob;// 如果已經(jīng)轉(zhuǎn)換就復(fù)用if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {ob = value.__ob__;} else if (//一堆必要的條件判斷observerState.shouldConvert &&!isServerRendering() &&(Array.isArray(value) || isPlainObject(value)) &&Object.isExtensible(value) &&!value._isVue) {//這才是observe主體ob = new Observer(value);}if (asRootData && ob) {ob.vmCount++;}return ob }

2.Observer 類

var Observer = function Observer (value) {// 當(dāng)asRootData = true時,其實可以將value當(dāng)做vm.$options.data,后面都這樣方便理解this.value = value;/*** 為vm.data創(chuàng)建一個dep實例,可以理解為一個專屬事件列表維護對象* 例如: this.dep = { id : 156, subs : [] }* 實例方法: this.dep.__proto__ = { addSub, removeSub, depend, notify, constructor }*/this.dep = new Dep();//記錄關(guān)聯(lián)的vm實例的數(shù)量this.vmCount = 0;//為vm.data 添加__ob__屬性,值為當(dāng)前observe實例,并且轉(zhuǎn)化為響應(yīng)式數(shù)據(jù)。所以看一個value是否為響應(yīng)式就可以看他有沒有__ob__屬性def(value, '__ob__', this);//響應(yīng)式數(shù)據(jù)轉(zhuǎn)換分為數(shù)組、對象兩種。if (Array.isArray(value)) {var augment = hasProto? protoAugment: copyAugment;augment(value, arrayMethods, arrayKeys);this.observeArray(value);} else {//對象的轉(zhuǎn)換,而且walk是Observer的實例方法,請記住this.walk(value);} };

3.walk

該方法要將vm.data的所有屬性都轉(zhuǎn)化為getter/setter模式,所以vm.data只能是Object。數(shù)組的轉(zhuǎn)換不一樣,這里暫不做講解。

Observer.prototype.walk = function walk (obj) {// 得到key的列表var keys = Object.keys(obj);for (var i = 0; i < keys.length; i++) {//核心方法:定義響應(yīng)式數(shù)據(jù)的方法 defineReactive(對象, 屬性, 值);這樣看是不是就很爽了defineReactive(obj, keys[i], obj[keys[i]]);} };

4.defineReactive(obj, key, value)

function defineReactive (obj,key,val,customSetter, //自定義setter,為了測試shallow //是否只轉(zhuǎn)換這一個屬性后代不管控制參數(shù),false :是,true : 否 ) {/*** 又是一個dep實例,其實作用與observe中的dep功能一樣,不同點:* 1.observe實例的dep對象是父級vm.data的訂閱者維護對象* 2.這個dep是vm.data的屬性key的訂閱者維護對象,因為val有可能也是對象* 3.這里的dep沒有寫this.dep是因為defineReactive是一個方法,不是構(gòu)造函數(shù),所以使用閉包鎖在內(nèi)存中*/var dep = new Dep();// 獲取key的屬性描述符var property = Object.getOwnPropertyDescriptor(obj, key);// 如果key屬性不可設(shè)置,則退出該函數(shù)if (property && property.configurable === false) {return}// 為了配合那些已經(jīng)的定義了getter/setter的情況var getter = property && property.get;var setter = property && property.set;//遞歸,因為沒有傳asRootData為true,所以vm.data的vmCount是部分計數(shù)的。因為它還是屬于vm的數(shù)據(jù)var childOb = !shallow && observe(val);/*** 全部完成后observe也就完成了。但是,每個屬性的dep都沒啟作用。* 這就是所謂的依賴收集了,后面繼續(xù)。*/Object.defineProperty(obj, key, {enumerable: true,configurable: true,get: function reactiveGetter () {var value = getter ? getter.call(obj) : val;if (Dep.target) {dep.depend();if (childOb) {childOb.dep.depend();if (Array.isArray(value)) {dependArray(value);}}}return value},set: function reactiveSetter (newVal) {var value = getter ? getter.call(obj) : val;/* eslint-disable no-self-compare */if (newVal === value || (newVal !== newVal && value !== value)) {return}/* eslint-enable no-self-compare */if (process.env.NODE_ENV !== 'production' && customSetter) {customSetter();}if (setter) {setter.call(obj, newVal);} else {val = newVal;}childOb = !shallow && observe(newVal);dep.notify();}}); }

三、依賴收集

一些個人理解:1、Watcher 訂閱者可以將它理解為,要做什么。具體的體現(xiàn)就是Watcher的第二個參數(shù)expOrFn。2、Observer 觀察者其實觀察的體現(xiàn)就是getter/setter能夠觀察數(shù)據(jù)的變化(數(shù)組的實現(xiàn)不同)。3、dependency collection 依賴收集訂閱者(Watcher)是干事情的,是一些指令、方法、表達式的執(zhí)行形式。它運行的過程中肯定離不開數(shù)據(jù),所以就成了這些數(shù)據(jù)的依賴項目。因為離不開^_^數(shù)據(jù)。數(shù)據(jù)是肯定會變的,那么數(shù)據(jù)變了就得通知數(shù)據(jù)的依賴項目(Watcher)讓他們再執(zhí)行一下。依賴同一個數(shù)據(jù)的依賴項目(Watcher)可能會很多,為了保證能夠都通知到,所以需要收集一下。4、Dep 依賴收集器構(gòu)造函數(shù)因為數(shù)據(jù)是由深度的,在不同的深度有不同的依賴,所以我們需要一個容器來裝起來。Dep.target的作用是保證數(shù)據(jù)在收集依賴項(Watcher)時,watcher是對這個數(shù)據(jù)依賴的,然后一個個去收集的。

1、Watcher

Watcher (vm, expOrFn, cb, options) 參數(shù): {string | Function} expOrFn {Function | Object} callback {Object} [options]{boolean} deep{boolean} user{boolean} lazy{boolean} sync 在Vue的整個生命周期當(dāng)中,會有4類地方會實例化Watcher:Vue實例化的過程中有watch選項Vue實例化的過程中有computed計算屬性選項Vue原型上有掛載$watch方法: Vue.prototype.$watch,可以直接通過實例調(diào)用this.$watch方法Vue生成了render函數(shù),更新視圖時Watcher接收的參數(shù)當(dāng)中expOrFn定義了用以獲取watcher的getter函數(shù)。expOrFn可以有2種類型:string或function.若為string類型, 首先會通過parsePath方法去對string進行分割(僅支持.號形式的對象訪問)。在除了computed選項外,其他幾種實例化watcher的方式都 是在實例化過程中完成求值及依賴的收集工作:this.value = this.lazy ? undefined : this.get().在Watcher的get方法中: var Watcher = function Watcher (vm,expOrFn,cb,options ) {this.vm = vm;vm._watchers.push(this);// optionsif (options) {this.deep = !!options.deep;this.user = !!options.user;this.lazy = !!options.lazy;this.sync = !!options.sync;} else {this.deep = this.user = this.lazy = this.sync = false;}//相關(guān)屬性this.cb = cb;this.id = ++uid$2; // uid for batchingthis.active = true;this.dirty = this.lazy; // for lazy watchers//this.deps = [];this.newDeps = [];//set類型的idsthis.depIds = new _Set();this.newDepIds = new _Set();// 表達式this.expression = process.env.NODE_ENV !== 'production'? expOrFn.toString(): '';// 創(chuàng)建一個getterif (typeof expOrFn === 'function') {this.getter = expOrFn;} else {this.getter = parsePath(expOrFn);if (!this.getter) {this.getter = function () {};process.env.NODE_ENV !== 'production' && warn("Failed watching path: \"" + expOrFn + "\" " +'Watcher only accepts simple dot-delimited paths. ' +'For full control, use a function instead.',vm);}}this.value = this.lazy? undefined: this.get();//執(zhí)行g(shù)et收集依賴項 };

2、Watcher.prototype.get

通過設(shè)置觀察值(this.value)調(diào)用this.get方法,執(zhí)行this.getter.call(vm, vm),這個過程中只要獲取了某個響應(yīng)式數(shù)據(jù)。那么肯定會觸發(fā)該數(shù)據(jù)的getter方法。因為當(dāng)前的Dep.target = watcher。所以就將該watcher作為了這個響應(yīng)數(shù)據(jù)的依賴項。因為watcher在執(zhí)行過程中的確需要、使用了它、所以依賴它。

Watcher.prototype.get = function get () {//將這個watcher觀察者實例添加到Dep.target,表明當(dāng)前為this.expressoin的依賴收集時間pushTarget(this);var value;var vm = this.vm;try {/*** 執(zhí)行this.getter.call(vm, vm):* 1、如果是function則相當(dāng)于vm.expOrFn(vm),只要在這個方法執(zhí)行的過程中有從vm上獲取屬性值的都會觸發(fā)該屬性值的get方法從而完成依賴收集。因為現(xiàn)在Dep.target=this. * 2、如果是字符串(如a.b),那么this.getter.call(vm, vm)就相當(dāng)于vm.a.b*/ value = this.getter.call(vm, vm);} catch (e) {if (this.user) {handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));} else {throw e}} finally {// "touch" every property so they are all tracked as// dependencies for deep watchingif (this.deep) {traverse(value);}popTarget();this.cleanupDeps();}return value };

3、getter/setter

Object.defineProperty(obj, key, {enumerable: true,configurable: true,get: function reactiveGetter () {var value = getter ? getter.call(obj) : val;if (Dep.target) {//依賴收集,這里又饒了一圈,看后面的解釋dep.depend();if (childOb) {childOb.dep.depend();if (Array.isArray(value)) {dependArray(value);}}}return value},set: function reactiveSetter (newVal) {var value = getter ? getter.call(obj) : val;/* eslint-disable no-self-compare */if (newVal === value || (newVal !== newVal && value !== value)) {return}/* eslint-enable no-self-compare */if (process.env.NODE_ENV !== 'production' && customSetter) {customSetter();}if (setter) {setter.call(obj, newVal);} else {val = newVal;}childOb = !shallow && observe(newVal);//數(shù)據(jù)變動出發(fā)所有依賴項dep.notify();}});

- 依賴收集具體動作:

//調(diào)用的自己dep的實例方法 Dep.prototype.depend = function depend () {if (Dep.target) {//調(diào)用的是當(dāng)前Watcher實例的addDe方法,并且把dep對象傳過去了Dep.target.addDep(this);} };Watcher.prototype.addDep = function addDep (dep) {var id = dep.id;if (!this.newDepIds.has(id)) {//為這個watcher統(tǒng)計內(nèi)部依賴了多少個數(shù)據(jù),以及其他公用該數(shù)據(jù)的watcherthis.newDepIds.add(id);this.newDeps.push(dep);if (!this.depIds.has(id)) {//繼續(xù)為數(shù)據(jù)收集依賴項目的步驟dep.addSub(this);}} }; Dep.prototype.addSub = function addSub (sub) {this.subs.push(sub); };

- 數(shù)據(jù)變動出發(fā)依賴動作:

Dep.prototype.notify = function notify () {// stabilize the subscriber list firstvar subs = this.subs.slice();for (var i = 0, l = subs.length; i < l; i++) {subs[i].update();} }; //對當(dāng)前watcher的處理 Watcher.prototype.update = function update () {/* istanbul ignore else */if (this.lazy) {this.dirty = true;} else if (this.sync) {this.run();} else {queueWatcher(this);} }; //把一個觀察者推入觀察者隊列。 //具有重復(fù)id的作業(yè)將被跳過,除非它是 //當(dāng)隊列被刷新時被推。 export function queueWatcher (watcher: Watcher) {const id = watcher.idif (has[id] == null) {has[id] = trueif (!flushing) {queue.push(watcher)} else {// if already flushing, splice the watcher based on its id// if already past its id, it will be run next immediately.let i = queue.length - 1while (i > index && queue[i].id > watcher.id) {i--}queue.splice(i + 1, 0, watcher)}// queue the flushif (!waiting) {waiting = truenextTick(flushSchedulerQueue)}} }

總結(jié)

以上是生活随笔為你收集整理的Vue2 源码漫游(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。