vue大前端react & vue & angular

Vue.js 源码分析——响应式原理

2022-02-27  本文已影响0人  丽__
一、准备工作
/* @flow */
function square(n:number):number{
  return n*n
}
square('a');  // error
二、调试设置
npm i
"dev":"rollup -w -c scripts/config.js --sourcemap --environment TARGET:web-fulol-dev"
三、 Vue的不同构建版本

术语

CommonJS 输出是值的拷贝,即原来模块中的值改变不会影响已经加载的该值,ES6静态分析,动态引用,输出的是值的引用,值改变,引用也改变,即原来模块中的值改变则该加载的值也改变。
CommonJS 模块是运行时加载,ES6 模块是编译时输出接口。
CommonJS 加载的是整个模块,即将所有的接口全部加载进来,ES6 可以单独加载其中的某个接口(方法),
CommonJS this 指向当前模块,ES6 this 指向undefined
CommonJS 模块输出的是一个值的拷贝,ES6 模块输出的是值的引用。

CommonJS 模块输出的是值的拷贝,也就是说,一旦输出一个值,模块内部的变化就影响不到这个值。ES6 模块的运行机制与 CommonJS 不一样。JS 引擎对脚本静态分析的时候,遇到模块加载命令import,就会生成一个只读引用。等到脚本真正执行时,再根据这个只读引用,到被加载的那个模块里面去取值。ES6 模块不会缓存运行结果,而是动态地去被加载的模块取值,并且变量总是绑定其所在的模块。
CommonJs模块化:
// lib.js
var counter = 3;
function incCounter() {
  counter++;
}
module.exports = {
  counter: counter,
  incCounter: incCounter,
};
// main.js
var mod = require('./lib');
 
console.log(mod.counter);  // 3
mod.incCounter();
console.log(mod.counter); // 3


ES6模块化
// lib.js
export let counter = 3;
export function incCounter() {
  counter++;
}
 
// main.js
import { counter, incCounter } from './lib';
console.log(counter); // 3
incCounter();
console.log(counter); // 4



从上面我们看出,CommonJS 模块输出的是值的拷贝,也就是说,一旦输出一个值,模块内部的变化就影响不到这个值。而ES6 模块是动态地去被加载的模块取值,并且变量总是绑定其所在的模块。

另外CommonJS 加载的是一个对象(即module.exports属性),该对象只有在脚本运行完才会生成。而 ES6 模块不是对象,它的对外接口只是一种静态定义,在代码静态解析阶段就会生成。

目前阶段,通过 Babel 转码,CommonJS 模块的require命令和 ES6 模块的import命令,可以写在同一个模块里面,但是最好不要这样做。因为import在静态解析阶段执行,所以它是一个模块之中最早执行的。
打开webpack的配置文件并且将结果输出到指定文件
 vue inspect > output.js
image.png
四、 寻找入口文件
npm run dev
"dev": "rollup -w -c scripts/config.js --sourcemap --environment TARGET:web-full-dev",

environment TARGET:web-full-dev  设置环境变量TARGET
//判断环境变量是否有TARGET
// 如果有的话使用getConfig() 生成rollup 配置文件
五、从入口开始
const vm =  new Vue({
  el:'#app',
  template:'<div class="div">template</div>',
  render(h){
      return h('div','hello template')
  }
})
六、Vue初始化过程

四个导出Vue的模块

七、Vue初始化 -- 两个问题

安装插件 ——>babel JavaScript


image.png
八、Vue初始化 —— 静态成员
image.png
九、Vue初始化 —— 实例成员
image.png
十、Vue初始化——实例成员init
/* @flow */

import config from '../config'
import { initProxy } from './proxy'
import { initState } from './state'
import { initRender } from './render'
import { initEvents } from './events'
import { mark, measure } from '../util/perf'
import { initLifecycle, callHook } from './lifecycle'
import { initProvide, initInjections } from './inject'
import { extend, mergeOptions, formatComponentName } from '../util/index'

let uid = 0

export function initMixin (Vue: Class<Component>) {
  // 给Vue实例增加 _init()方法
  // 合并options / 初始化操作
  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
    // 如果是Vue实例不需要被observe
    vm._isVue = true
    // merge options
    // 合并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
    // vm 的生命周期相关变量初始化$children /$parent/$root/$refs
    initLifecycle(vm)
    // vm的时间监听初始化,父组件绑定在当前组件上的时间
    initEvents(vm)
    // vm 的编译render初始化 $slots/$scopedSlots/_c/$createElement/$attrs/$listeners
    initRender(vm)
    // beforeCreate生命周期的回调
    callHook(vm, 'beforeCreate')
    // 把inject的成员注入到vm上
    initInjections(vm) // resolve injections before data/props
    // 初始化vm的_props/methods/_data/computed/watch
    initState(vm)
    // 初始化provide
    initProvide(vm) // resolve provide after data/props
    // created生命钩子的回调
    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)
    }
  }
}

export function initInternalComponent (vm: Component, options: InternalComponentOptions) {
  const opts = vm.$options = Object.create(vm.constructor.options)
  // doing this because it's faster than dynamic enumeration.
  const parentVnode = options._parentVnode
  opts.parent = options.parent
  opts._parentVnode = parentVnode

  const vnodeComponentOptions = parentVnode.componentOptions
  opts.propsData = vnodeComponentOptions.propsData
  opts._parentListeners = vnodeComponentOptions.listeners
  opts._renderChildren = vnodeComponentOptions.children
  opts._componentTag = vnodeComponentOptions.tag

  if (options.render) {
    opts.render = options.render
    opts.staticRenderFns = options.staticRenderFns
  }
}

export function resolveConstructorOptions (Ctor: Class<Component>) {
  let options = Ctor.options
  if (Ctor.super) {
    const superOptions = resolveConstructorOptions(Ctor.super)
    const cachedSuperOptions = Ctor.superOptions
    if (superOptions !== cachedSuperOptions) {
      // super option changed,
      // need to resolve new options.
      Ctor.superOptions = superOptions
      // check if there are any late-modified/attached options (#4976)
      const modifiedOptions = resolveModifiedOptions(Ctor)
      // update base extend options
      if (modifiedOptions) {
        extend(Ctor.extendOptions, modifiedOptions)
      }
      options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)
      if (options.name) {
        options.components[options.name] = Ctor
      }
    }
  }
  return options
}

function resolveModifiedOptions (Ctor: Class<Component>): ?Object {
  let modified
  const latest = Ctor.options
  const sealed = Ctor.sealedOptions
  for (const key in latest) {
    if (latest[key] !== sealed[key]) {
      if (!modified) modified = {}
      modified[key] = latest[key]
    }
  }
  return modified
}

十一、Vue首次渲染过程
image.png
image.png
image.png
十二、数据响应式原理——响应式处理入口
//数据的初始化
if(opts.data){
  initData(vm)
} else {
  observe(vm._data = {} , true )
}
十三、watcher类
十四、数据响应式原理-总结
image.png
image.png
image.png
image.png
image.png
image.png
十五、set - 源码
//静态方法  set / delete/nextTick
Vue.set = set
Vue.delete = del
Vue.nextTick = nextTick
//注册vm 的$data/$props/$set/#delete/$watch
//instance/state.js
stateMixin(Vue)

//instance/state.js
Vue.prototype.$set = set
Vue.prototype.$delete = delete
十六、delete - vm.$delete
vm.$delete(vm.obj,'msg')
// 静态方法 set/delete/nextTick
  Vue.set = set
  Vue.delete = del
  Vue.nextTick = nextTick
//注册vm 的$data/$props/$set/#delete/$watch
stateMixin(Vue)

/instance/state.js
Vue.prototype.$set = set
Vue.prototype.$delete = delete
十七、watch- vm.$watch
const vm = new Vue({
  el:'#app',
  data:{
    user:{
      firstName:'诸葛',
      lastName:'亮',
      fullName:''
    }
  }
})

vm.$watch('user',function(newValue,oldValue){
  this.user.fullName = newValue.firstName + ' ' + newValue.lastName
},{
  immediate:'true',//是否立即执行一次回调函数
  deep:'true',//深度监听
})
十八、三种类型的Watcher对象
十九、异步更新队列——nextTick()
<template>
  <div id="app">
    <p ref="p1">{{ msg }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      msg: "hello nextTick",
      name: "Vue.js",
      title: "Title",
    };
  },
  mouinted() {
    (this.msg = "hello world"), (this.name = "hello snabbdom");
    this.title = "vue.js";

    this.$nextTick(() => {
      console.log(this.$refs.p1.textContent);
    });
  },
};
</script>
  Vue.prototype.$nextTick = function (fn: Function) {
    return nextTick(fn, this)
  }
上一篇 下一篇

猜你喜欢

热点阅读