这一节主要记录一下:Vue 的初始化过程

以下正式开始:

Vue官网的生命周期图示表

Vue源码分析之Vue实例初始化详解

重点说一下 new Vue()后的初始化阶段,也就是created之前发生了什么。

Vue源码分析之Vue实例初始化详解

initLifecycle 阶段

export function initLifecycle (vm: Component) {
 const options = vm.$options

 // locate first non-abstract parent
 let parent = options.parent
 if (parent && !options.abstract) {
  while (parent.$options.abstract && parent.$parent) {
   parent = parent.$parent
  }
  parent.$children.push(vm) // 自己把自己添加到父级的$children数组中
 }

 vm.$parent = parent // 父组件实例
 vm.$root = parent "htmlcode">
// v-on如果写在平台标签上如:div,则会将v-on上注册的事件注册到浏览器事件中
// v-on如果写在组件标签上,则会将v-on注册的事件注册到子组件的事件系统
// 子组件(Vue实例)在初始化的时候,有可能接收到父组件向子组件注册的事件。
// 子组件(Vue实例)自身模板注册的事件,只要在渲染的时候才会根据虚拟DOM的对比结果
// 来确定是注册事件还是解绑事件

// 这里初始化的事件是指父组件在模板中使用v-on注册的事件添加到子组件的事件系统也就是vue的事件系统。
export function initEvents (vm: Component) {
 vm._events = Object.create(null) // 初始化
 vm._hasHookEvent = false
 // init parent attached events 初初始化腹肌组件添加的事件
 const listeners = vm.$options._parentListeners
 if (listeners) {
  updateComponentListeners(vm, listeners)
 }
}

export function updateComponentListeners (
 vm: Component,
 listeners: Object,
 oldListeners: "htmlcode">
export function initInjections (vm: Component) {
 // 自下而上读取inject
 const result = resolveInject(vm.$options.inject, vm)
 if (result) {
  // 设置为false 避免defineReactive函数把数据转换为响应式
  toggleObserving(false)
  Object.keys(result).forEach(key => {
    defineReactive(vm, key, result[key])
  })
  // 再次更改回来
  toggleObserving(true)
 }
}

export function resolveInject (inject: any, vm: Component): "${key}" not found`, vm)
    }
   }
  }
  return result
 }
}

initState 阶段

在 Vue 中,我们经常会用到 props 、methods 、 watch 、computed 、data 。这些状态在使用前都需要初始化。而初始化的过程正是在 initState 阶段完成。

因为 injects 是在 initState 之前完成,所以可以在 State 中使用 injects 。

export function initState (vm: Component) {
 vm._watchers = []
 // 获取到经过初始化的用户传进来的options
 const opts = vm.$options
 if (opts.props) initProps(vm, opts.props)
 if (opts.methods) initMethods(vm, opts.methods)
 if (opts.data) {
  initData(vm)
 } else {
  observe(vm._data = {}, true /* asRootData */)
 }
 if (opts.computed) initComputed(vm, opts.computed)
 if (opts.watch && opts.watch !== nativeWatch) {
  initWatch(vm, opts.watch)
 }
}

initProps

function initProps (vm: Component, propsOptions: Object) {
 const propsData = vm.$options.propsData || {}
 const props = vm._props = {}
 // cache prop keys so that future props updates can iterate using Array
 // instead of dynamic object key enumeration.
 // 缓存props的key值
 const keys = vm.$options._propKeys = []
 const isRoot = !vm.$parent
 // root instance props should be converted
 // 如果不是跟组件则没必要转换成响应式数据
 if (!isRoot) {
  // 控制是否转换成响应式数据
  toggleObserving(false)
 }
 for (const key in propsOptions) {
  keys.push(key)
  // 获取props的值
  const value = validateProp(key, propsOptions, propsData, vm)
  defineReactive(props, key, value)
  // static props are already proxied on the component's prototype
  // during Vue.extend(). We only need to proxy props defined at
  // instantiation here.
  // 把props代理到Vue实例上来,可以直接通过this.props访问
  if (!(key in vm)) {
   proxy(vm, `_props`, key)
  }
 }
 toggleObserving(true)
}

initMethods

function initMethods (vm: Component, methods: Object) {
 const props = vm.$options.props
 for (const key in methods) {
  if (process.env.NODE_ENV !== 'production') {
   // 如果key不是一个函数 报错
   if (typeof methods[key] !== 'function') {
    warn(
     `Method "${key}" has type "${typeof methods[key]}" in the component definition. ` +
     `Did you reference the function correctly"${key}" has already been defined as a prop.`,
     vm
    )
   }
   // isReserved判断是否以$或_开头
   if ((key in vm) && isReserved(key)) {
    warn(
     `Method "${key}" conflicts with an existing Vue instance method. ` +
     `Avoid defining component methods that start with _ or $.`
    )
   }
  }
  // 把methods的方法绑定到Vue实例上
  vm[key] = typeof methods[key] !== 'function' "htmlcode">
function initData (vm: Component) {
 let data = vm.$options.data
 data = vm._data = typeof data === 'function'
  "${key}" has already been defined as a data property.`,
     vm
    )
   }
  }
  // 如果在props中存在和key同名的属性 则报错
  if (props && hasOwn(props, key)) {
   process.env.NODE_ENV !== 'production' && warn(
    `The data property "${key}" is already declared as a prop. ` +
    `Use prop default value instead.`,
    vm
   )
  } else if (!isReserved(key)) {
   // isReserved判断是否以$或_开头
   // 代理data,使得可以直接通过this.key访问this._data.key
   proxy(vm, `_data`, key)
  }
 }
 // observe data
 // 把data转换为响应式数据
 observe(data, true /* asRootData */)
}

initComputed

const computedWatcherOptions = { lazy: true }
function initComputed (vm: Component, computed: Object) {
 // $flow-disable-line
 const watchers = vm._computedWatchers = Object.create(null)
 // computed properties are just getters during SSR
 // 判断是不是服务端渲染
 const isSSR = isServerRendering()

 for (const key in computed) {
  const userDef = computed[key]
  const getter = typeof userDef === 'function' "${key}".`,
    vm
   )
  }
  // 如果不是ssr,则创建Watcher实例
  if (!isSSR) {
   // create internal watcher for the computed property.
   watchers[key] = new Watcher(
    vm,
    getter || noop,
    noop,
    computedWatcherOptions
   )
  }

  // component-defined computed properties are already defined on the
  // component prototype. We only need to define computed properties defined
  // at instantiation here.
  // 如果vm不存在key的同名属性
  if (!(key in vm)) {
   defineComputed(vm, key, userDef)
  } else if (process.env.NODE_ENV !== 'production') {
   if (key in vm.$data) {
    warn(`The computed property "${key}" is already defined in data.`, vm)
   } else if (vm.$options.props && key in vm.$options.props) {
    warn(`The computed property "${key}" is already defined as a prop.`, vm)
   }
  }
 }
}
sharedPropertyDefinition = {
  enumerable: true,
  cnfigurable: true,
  get: noop,
  set: noop
}
export function defineComputed (
 target: any,
 key: string,
 userDef: Object | Function
) {
 // 如果是服务端渲染,则computed不会有缓存,因为数据响应式的过程在服务器是多余的
 const shouldCache = !isServerRendering()
 // createComputedGetter返回计算属性的getter
 // createGetterInvoker返回userDef的getter
 if (typeof userDef === 'function') {
  sharedPropertyDefinition.get = shouldCache
   "${key}" was assigned to but it has no setter.`,
    this
   )
  }
 }
 // 在tearget上定义一个属性, 属性名为key, 属性描述符为sharedPropertyDefinition
 Object.defineProperty(target, key, sharedPropertyDefinition)
}

function createComputedGetter (key) {
 return function computedGetter () {
  // 查找是否存在key的Watcher
  const watcher = this._computedWatchers && this._computedWatchers[key]
  if (watcher) {
   // 如果dirty为true,则重新计算,否则返回缓存
   if (watcher.dirty) {
    watcher.evaluate()
   }
   if (Dep.target) {
    watcher.depend()
   }
   return watcher.value
  }
 }
}

function createGetterInvoker(fn) {
 return function computedGetter () {
  return fn.call(this, this)
 }
}

initWatch

function initWatch (vm: Component, watch: Object) {
 for (const key in watch) {
  const handler = watch[key]
  // 处理数组类型
  if (Array.isArray(handler)) {
   for (let i = 0; i < handler.length; i++) {
    createWatcher(vm, key, handler[i])
   }
  } else {
   createWatcher(vm, key, handler)
  }
 }
}

function createWatcher (
 vm: Component,
 expOrFn: string | Function,
 handler: any,
 options"htmlcode">
export function initProvide (vm: Component) {
 const provide = vm.$options.provide
 if (provide) {
  // 把provided存到_provided上
  vm._provided = typeof provide === 'function'
   "color: #ff0000">总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。