溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

this為什么指向vue實例

發(fā)布時間:2022-01-20 10:58:39 來源:億速云 閱讀:241 作者:小新 欄目:編程語言

這篇文章主要為大家展示了“this為什么指向vue實例”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“this為什么指向vue實例”這篇文章吧。

拋出問題

正常開發(fā)vue代碼,大差不差都會這么寫

export default {
    data() {
        return {
            name: '彭魚宴'
        }
    },
    methods: {
        greet() {
            console.log(`hello, 我是${this.name}`)
        }
    }
}

為什么這里的this.name可以直接訪問到data里定義的name呢,或者this.someFn可以直接訪問到methods里定義的函數(shù)呢,帶著這個問題開始看vue2.x的源碼找答案。

源碼分析

這里先貼個vue的源碼地址vue源碼。我們先看看vue實例的構造函數(shù),構造函數(shù)在源碼的目錄/vue/src/core/instance/index.js下,代碼量不多,全部貼出來看看

function Vue (options) {
  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)
}

initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

export default Vue

構造函數(shù)很簡單,if (!(this instanceof Vue)){} 判斷是不是用了 new 關鍵詞調(diào)用構造函數(shù),沒有則拋出warning,這里的this指的是Vue的一個實例。如果正常使用了new關鍵詞,就走_init函數(shù),是不是很簡單。

_init函數(shù)分析

let uid = 0

export function initMixin (Vue: Class<Component>) {
  Vue.prototype._init = function (options?: Object) {
    const vm: Component = this
    // a uid
    vm._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 observed
    vm._isVue = 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.
      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 self
    vm._self = vm
    initLifecycle(vm)
    initEvents(vm)
    initRender(vm)
    callHook(vm, 'beforeCreate')
    initInjections(vm) // resolve injections before data/props
    initState(vm)
    initProvide(vm) // resolve provide after data/props
    callHook(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)
    }
  }
}

_init函數(shù)有點長,做了很多事情,這里就不一一解讀,和我們此次探索相關的內(nèi)容應該在initState(vm)這個函數(shù)中,我們繼續(xù)到initState這個函數(shù)里看看。

initState函數(shù)分析

export function initState (vm: Component) {
  vm._watchers = []
  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)
  }
}

可以看出initState做了5件事情

  • 初始化props

  • 初始化methods

  • 初始化data

  • 初始化computed

  • 初始化watch

我們先重點看看初始化methods做了什么

initMethods 初始化方法

function initMethods (vm, methods) {
    var props = vm.$options.props;
    for (var key in methods) {
      {
        if (typeof methods[key] !== 'function') {
          warn(
            "Method \"" + key + "\" has type \"" + (typeof methods[key]) + "\" in the component definition. " +
            "Did you reference the function correctly?",
            vm
          );
        }
        if (props && hasOwn(props, key)) {
          warn(
            ("Method \"" + key + "\" has already been defined as a prop."),
            vm
          );
        }
        if ((key in vm) && isReserved(key)) {
          warn(
            "Method \"" + key + "\" conflicts with an existing Vue instance method. " +
            "Avoid defining component methods that start with _ or $."
          );
        }
      }
      vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm);
    }
}

initMethods主要是一些判斷:

判斷methods中定義的函數(shù)是不是函數(shù),不是函數(shù)就拋warning;
判斷methods中定義的函數(shù)名是否與props沖突,沖突拋warning;
判斷methods中定義的函數(shù)名是否與已經(jīng)定義在Vue實例上的函數(shù)相沖突,沖突的話就建議開發(fā)者用_或者$開頭命名;

除去上述說的這些判斷,最重要的就是在vue實例上定義了一遍methods里所有的方法,并且使用bind函數(shù)將函數(shù)的this指向Vue實例上,就是我們new Vue()的實例對象上。

這就解釋了為啥this可以直接訪問到methods里的方法。

initData 初始化數(shù)據(jù)

function initData (vm) {
    var data = vm.$options.data;
    data = vm._data = typeof data === 'function'
      ? getData(data, vm)
      : data || {};
    if (!isPlainObject(data)) {
      data = {};
      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
    var keys = Object.keys(data);
    var props = vm.$options.props;
    var methods = vm.$options.methods;
    var i = keys.length;
    while (i--) {
      var key = keys[i];
      {
        if (methods && hasOwn(methods, key)) {
          warn(
            ("Method \"" + key + "\" has already been defined as a data property."),
            vm
          );
        }
      }
      if (props && hasOwn(props, key)) {
        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
    observe(data, true /* asRootData */);
}

initdata做了哪些事情呢:

  • 先在實例 _data 上賦值,getData函數(shù)處理 data 這個 function,返回的是一個對象

  • 判斷最終獲取到的 data, 不是對象給出警告。

  • 判斷methods里的函數(shù)和data里的key是否有沖突

  • 判斷props和data里的key是否有沖突

  • 判斷是不是內(nèi)部私有的保留屬性,若不是就做一層代理,代理到 _data 上

  • 最后監(jiān)聽data,使之成為響應式數(shù)據(jù)

再看下proxy函數(shù)做了什么:

function noop (a, b, c) {}
var sharedPropertyDefinition = {
    enumerable: true,
    configurable: true,
    get: noop,
    set: noop
};

function proxy (target, sourceKey, key) {
    sharedPropertyDefinition.get = function proxyGetter () {
      return this[sourceKey][key]
    };
    sharedPropertyDefinition.set = function proxySetter (val) {
      this[sourceKey][key] = val;
    };
    Object.defineProperty(target, key, sharedPropertyDefinition);
}

其實這里的Object.defineProperty就是用來定義對象的

proxy的用處就是使this.name指向this._data.name

以上是“this為什么指向vue實例”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI