current position:Home>vue 2. What happens when x source code analyzes new vue()

vue 2. What happens when x source code analyzes new vue()

2022-04-29 04:28:22@huihui_ new

1. Data driven

Vue A core idea of the framework is data-driven view . What is data driven view ? Simple understanding , When we want to change the browser view , Just by modifying the data . This process , It greatly simplifies the amount of code of traditional front-end development , Thus, there is no need to consider DOM Modification of , No need to consider complex DOM operation , Just focus the logic on the change of data .

So how is this achieved ? In fact, it can be divided into two scenarios to analyze :

1.1 The process of the first rendering of the page

For example, the following code :

<div id="app">
  {
   { message }}
</div>
var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})

How do these seemingly very simple code render to the browser page ?

1.2 Changing data triggers view updates

<div id="app">
  {
   { message }}
</div>
<button @click="handleClick"></button>
var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  methods: {
      handleClick() {
          this.message = 'Hello huihui_new'
      }
  }
})

Another example is that we click the button to change message Value , The page immediately updated , How does this process happen ?

If these two processes are clear , Yes vue Your understanding will certainly be deeper .

So how to analyze these two processes , Then start reading the source code

2.new Vue() What happened when

What happened? ? So let's start with 1.1 To analyze the code in ,new Vue(options) What happened when I was .

stay src/core/instance Under the directory of , There's the following code :

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) {
    
  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;

You can see , Here is the definition of Vue Constructors , So externally we have to use new To instantiate Vue, Instantiation Vue In the process of _init(options) Method (options It is the configuration object passed in when we instantiate ).

init() The method is in initMixin(Vue) In the process of mounting to vue above ,

export function initMixin(Vue: Class<Component>) {
    
  //  Mount to vue On 
  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  Merge configuration 
    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;
    //  initialization 
    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);
    }
  };
}

In the process I did a few things :

  1. Merge configuration ;
  2. Initialize the lifecycle 、 Initialize the event center 、 Initialize rendering , initialization data、props、computed、watcher etc. ;
  3. mount ;

that data How to render to the page , Let's keep looking at the source code , In the second step above initState(vm), Initialized the incoming data configuration , The code is as follows :

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)
  }
}

It's initialized props、methods、data etc. , In our example, data is passed in , Then initialize the data , perform initData() Method ;

function initData (vm: Component) {
    
  let data = vm.$options.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') {
    
      if (methods && hasOwn(methods, key)) {
    
        warn(
          `Method "${
      key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    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
  observe(data, true /* asRootData */)
}

It is mainly divided into 4 Step :

  1. First, determine whether the definition is a function , If so, execute the function , Gets the returned data object ;
  2. Judgment and definition methods、props Is there a conflict ;
  3. Proxy data properties :
proxy(vm, `_data`, key)

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

adopt defineProperty This API Yes vm._data.key Acting as agent , So you can get through vm.key Access to di It's defined in data Properties in , Convenient for users

  1. Monitor data
    The logic here is mainly to deeply monitor the data , To achieve responsive , We'll analyze this later .

So far we know new Vue() How is it? initData 了 , Next, continue to analyze data How to mount to the page !!!
To be continued !!!

copyright notice
author[@huihui_ new],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/117/202204270551339151.html

Random recommended