文件:vue\src\core\instance\init.js
- export function initMixin (Vue: Class<Component>) {
- Vue.prototype._init = function (options?: Object) {
- ...
- // 初始化过程
- vm._self = vm
- initLifecycle(vm) // 初始化相关生命周期属性 $children、$root、$children、$refs
- initEvents(vm) // 自定义事件监听
- initRender(vm) // 插槽解析($slots)。 render(h)方法里的h:_c() 和 $createElement()
- callHook(vm, 'beforeCreate') // 生命周期钩子:beforeCreate
- // 初始化组件各种状态、响应式处理
- initInjections(vm) // resolve injections before data/props
- initState(vm) // props、methods、data、computed、watch
- initProvide(vm) // resolve provide after data/props
- callHook(vm, 'created')// 生命周期钩子:created
- }
- }
initState(vm) 函数中执行,继续往下
文件:vue\src\core\instance\state.js
- export function initState (vm: Component) {
- vm._watchers = []
- const opts = vm.$options
- // props、methods、data处理,优先级p》m》d
- 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)
- }
- }
找到重点函数:initData(vm)
- function initData (vm: Component) {
- let data = vm.$options.data
- // 判断data是函数还是其他
- data = vm._data = typeof data === 'function'
- ? getData(data, vm)
- : data || {}
- if (!isPlainObject(data)) {
- data = {}
- process.env.NODE_ENV !== 'production' && warn(
- 'data functions should return an object:\n' +
- 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
- vm
- )
- }
- // 边界判断
- // proxy data on instance
- const keys = Object.keys(data)
- const props = vm.$options.props
- const methods = vm.$options.methods
- let i = keys.length
- while (i--) {
- const key = keys[i]
- if (process.env.NODE_ENV !== 'production') {
- // 判断data是否与methods里的重名
- if (methods && hasOwn(methods, key)) {
- warn(
- `Method "${key}" has already been defined as a data property.`,
- vm
- )
- }
- }
- // 判断data是否与props里的重名
- 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)) {
- proxy(vm, `_data`, key)
- }
- }
- // observe data
- // 递归,对data 进行响应式处理
- observe(data, true /* asRootData */)
- }
最后observe(data, true /* asRootData */) 函数对象data进行响应处理
该函数文件:vue\src\core\observer\index.js
- export function observe (value: any, asRootData: ?boolean): Observer | void {
- // 不是对象 或者 虚拟dom实例 return
- if (!isObject(value) || value instanceof VNode) {
- return
- }
- // 1.响应式。2.动态属性的加入或删除,数组的加入或删除的变更通知。
- let ob: Observer | void
- // 判断是否有__ob__,如果是响应式对象,直接返回,不做重复处理
- if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
- ob = value.__ob__
- } else if (
- shouldObserve &&
- !isServerRendering() &&
- (Array.isArray(value) || isPlainObject(value)) &&
- Object.isExtensible(value) &&
- !value._isVue
- ) {
- // 初始化传入需要响应式的对象
- ob = new Observer(value)
- }
- if (asRootData && ob) {
- ob.vmCount++
- }
- return ob
- }
observe 函数将传入vlaue进行响应式处理 ob = new Observer(value)
- /**
- * Observer class that is attached to each observed
- * object. Once attached, the observer converts the target
- * object's property keys into getter/setters that
- * collect dependencies and dispatch updates.
- */
- export class Observer {
- value: any;
- dep: Dep;
- vmCount: number; // number of vms that have this object as root $data
-
- constructor (value: any) {
- this.value = value
- // 2. dep? 如果使用Vue.set/delete 添加或删除属性,负责通知更新
- this.dep = new Dep()
- this.vmCount = 0
- def(value, '__ob__', this)
- // 1. 分辨传入对象类型
- // 如果是数组
- if (Array.isArray(value)) {
- if (hasProto) {
- protoAugment(value, arrayMethods)
- } else {
- copyAugment(value, arrayMethods, arrayKeys)
- }
- this.observeArray(value)
- } else {
- // 是对象
- this.walk(value)
- }
- }
-
- /**
- * Walk through all properties and convert them into
- * getter/setters. This method should only be called when
- * value type is Object.
- */
- walk (obj: Object) {
- const keys = Object.keys(obj)
- for (let i = 0; i < keys.length; i++) {
- defineReactive(obj, keys[i])
- }
- }
-
- /**
- * Observe a list of Array items.
- */
- observeArray (items: Array
) { - for (let i = 0, l = items.length; i < l; i++) {
- observe(items[i])
- }
- }
- }
- export function defineReactive (
- obj: Object,
- key: string,
- val: any,
- customSetter?: ?Function,
- shallow?: boolean
- ) {
- // 每一个key对应一个dep
- const dep = new Dep()
-
- const property = Object.getOwnPropertyDescriptor(obj, key)
- if (property && property.configurable === false) {
- return
- }
-
- // cater for pre-defined getter/setters
- const getter = property && property.get
- const setter = property && property.set
- if ((!getter || setter) && arguments.length === 2) {
- val = obj[key]
- }
- // 递归处理
- let childOb = !shallow && observe(val)
- Object.defineProperty(obj, key, {
- enumerable: true,
- configurable: true,
- // 一个组件一个watcher
- get: function reactiveGetter () {
- const value = getter ? getter.call(obj) : val
- // 如果存在,说明此次调用触发者是一个Watcher实例
- if (Dep.target) {
- // 建立dep 和 Dep.target 之间依赖关系
- dep.depend()
- if (childOb) {
- // 建立ob 内部dep 和 Dep.target 之间依赖关系
- childOb.dep.depend()
- // 如果是数组,数组内部所有项都要做相同处理
- if (Array.isArray(value)) {
- dependArray(value)
- }
- }
- }
- return value
- },
- set: function reactiveSetter (newVal) {
- const 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()
- }
- // #7981: for accessor properties without setter
- if (getter && !setter) return
- if (setter) {
- setter.call(obj, newVal)
- } else {
- val = newVal
- }
- childOb = !shallow && observe(newVal)
- dep.notify()
- }
- })
- }
主要是进行依赖收集,实现n(Dep): n(Watcher)关系。
- /**
- * Collect dependencies on array elements when the array is touched, since
- * we cannot intercept array element access like property getters.
- */
- function dependArray (value: Array
) { - for (let e, i = 0, l = value.length; i < l; i++) {
- e = value[i]
- e && e.__ob__ && e.__ob__.dep.depend()
- if (Array.isArray(e)) {
- dependArray(e)
- }
- }
- }
并会进行protoAugment(value, arrayMethods) 覆盖数组7个方法
- function protoAugment (target, src: Object) {
- /* eslint-disable no-proto */
- // 覆盖当前数组实例的原型
- // 只会影响当前数组实例本身
- target.__proto__ = src
- /* eslint-enable no-proto */
- }
通过传入一个arrayMethods
import { arrayMethods } from './array'
找到该文件地址:vue\src\core\observer\array.js
- /*
- * not type checking this file because flow doesn't play well with
- * dynamically accessing methods on Array prototype
- */
-
- import { def } from '../util/index'
-
- const arrayProto = Array.prototype
- // 数组原型备份
- export const arrayMethods = Object.create(arrayProto)
-
- const methodsToPatch = [
- 'push',
- 'pop',
- 'shift',
- 'unshift',
- 'splice',
- 'sort',
- 'reverse'
- ]
-
- /**
- * Intercept mutating methods and emit events
- */
- methodsToPatch.forEach(function (method) {
- // cache original method
- const original = arrayProto[method]
- def(arrayMethods, method, function mutator (...args) {
- // 执行原始行为
- const result = original.apply(this, args)
- // 变更通知
- // 1. 获取ob 实例
- const ob = this.__ob__
- // 如果是新增元素的操作:比如push、unshift、splice 对该元素进行响应式observeArray
- let inserted
- switch (method) {
- case 'push':
- case 'unshift':
- inserted = args
- break
- case 'splice':
- inserted = args.slice(2)
- break
- }
- if (inserted) ob.observeArray(inserted)
- // notify change
- // 让内部的dep 通知更新
- ob.dep.notify()
- return result
- })
- })