得鹿梦鱼 得鹿梦鱼

初始化选项式api

initProps

function initPropsvm, propsOptions{    const propsData = vm.$options.propsData  {}    const props = vm._props = shallowReactive{}    const keys = vm.$options._propKeys = [];    if/* 是否是根组件 */{        // 关闭对象的递归响应    }    forconst key in propsOptions{        keys.pushkey        const value = validatePropkey, propsOptions, propsData, vm        defineReactiveprops, key, value, undefined, true /* shallow */    }    // 将组件的静态属性新增到vm._props对象中    if key in vm {      proxyvm, `_props`, key    }    // 开启对象的递归响应}

initMethods

function initMethodsvm, methods{    const props = vm.$options.props    forconst key in methods{        vm[key] = typeof methods[key] !== 'function' ? noop : bindmethods[key], vm    }}

initData

function initDatavm{    let data = vm.$options.data;    data = vm._data = isFunctiondata ? getDatadata, vm : data  {}    const keys = Object.keysdata    const props = vm.$options.props    const methods = vm.$options.methods    let i = keys.length    while i-- {        const key = keys[i]        if !isReservedkey {            proxyvm, `_data`, key        }    }    const ob = observedata    ob && ob.vmCount++}

initComputed

  1. 判断是不是服务器渲染
  2. 新增观察者
  3. 定义computed
function initComputedvm, computed{    const watchers = vm._computedWatchers = Object.createnull    const isSSR = isServerRendering    for const key in computed {        const userDef = computed[key]        const getter = isFunctionuserDef ? userDef : userDef.get        if !isSSR {            watchers[key] = new Watcher vm,getter  noop,noop,computedWatcherOptions        }        if !key in vm {            defineComputedvm, key, userDef        }    }}

initWatch

function initWatchvm, watch{for const key in watch {    const handler = watch[key]    if isArrayhandler {        for let i = 0; i < handler.length; i++ {            createWatchervm, key, handler[i]        }    } else {        createWatchervm, key, handler    }  }}