小程序开发|小程序制作|小程序开发网

搜索

Vue 和 Vue.prototype是怎么一步一步“丰富”起来的(1)

2022-6-2 17:26| 发布者: yangyuan| 查看: 354| 评论: 0

摘要: vue 可以运行在 web 平台和 weex 平台,以 web 平台为例,从它的入口文件开始:一看,怎么有好几个,它们的区别具体可参考:https://cn.vuejs.org/v2/guide/installation.html#%E5%AF%B9%E4%B8%8D%E5%90%8C%E6%9E%84

vue 可以运行在 web 平台和 weex 平台,以 web 平台为例,从它的入口文件开始:


一看,怎么有好几个,它们的区别具体可参考:https://cn.vuejs.org/v2/guide/installation.html#%E5%AF%B9%E4%B8%8D%E5%90%8C%E6%9E%84%E5%BB%BA%E7%89%88%E6%9C%AC%E7%9A%84%E8%A7%A3%E9%87%8A,我们这里不做赘述。

选择其中一个入口src\platforms\web\entry-runtime-with-compiler.js
我们重点关注Vue的变化,查看源码可知

  • src\platforms\web\entry-runtime-with-compiler.js里引用了src\platforms\web\runtime\index.js,重写了Vue.prototype.$mount
  • src\platforms\web\runtime\index.js里引用了src\core\index.js,在Vue.prototype挂载了$mounted方法,并对Vue.config进行配置等
  • src\core\index.js里引用了src\core\instance\index.js, 并调用initGlobalAPI(Vue)进行全局API初始化

那么,为了弄清楚我们的Vue是怎么一步步变得复杂起来,我们当然是从最简单的src\core\instance\index.js开始查看啦

src\core\instance\index.js

经过上面的步骤,Vue 的原型变成:


于是我们开始查看第二个文件src\core\index.js

src\core\index.js

由上可知先执行了initGlobalAPI(Vue), 于是我们重点关注这个方法

initGlobalAPI(Vue)

位置:src\core\global-api\index.js

 config  if (process.env.NODE_ENV !== 'production') {    configDef.set = () => {      warn(        'Do not replace the Vue.config object, set individual fields instead.'      )    }  }  Object.defineProperty(Vue, 'config', configDef) // 这一步在Vue上(注意不是Vue.prototype)挂载了静态属性config  // exposed util methods.  // NOTE: these are not considered part of the public API - avoid relying on  // them unless you are aware of the risk.  Vue.util = {    warn,    extend,    mergeOptions,    defineReactive  }  Vue.set = set  Vue.delete = del  Vue.nextTick = nextTick  // 2.6 explicit observable API  Vue.observable = (obj: T): T => {    observe(obj)    return obj  }  Vue.options = Object.create(null)  ASSET_TYPES.forEach(type => {    Vue.options[type + 's'] = Object.create(null)  })  // this is used to identify the "base" constructor to extend all plain-object  // components with in Weex's multi-instance scenarios.  Vue.options._base = Vue  extend(Vue.options.components, builtInComponents)  initUse(Vue) // Vue上挂载use  initMixin(Vue) // Vue上挂载mixin  initExtend(Vue) // Vue上挂载extend  initAssetRegisters(Vue) // vue上挂载directives,filters,components}

initGlobalAPI 对 Vue 做了什么?

  1. 在 Vue 上挂载config属性,即

  2. 在 Vue 上挂载了util, set, delete, nextTick, observable, use, mixin, extend, cid, directives, filters, components方法


  3. 在 Vue 上挂载了 options, options 的值即


    另外,options._base = Vue

initGlobalAPI 的分析到此为止, 接下来看src\core\index.js还做了哪些事情?

  • Vue上挂载FunctionalRenderContext
  • Vue.prototype上挂载 $isServer,$ssrContext

接下来我们分析第3个文件。

src\platforms\web\runtime\index.js

 {    if (config.devtools) {      if (devtools) { // 使用Vue开发工具插件        devtools.emit('init', Vue)      } else if (        process.env.NODE_ENV !== 'production' &&        process.env.NODE_ENV !== 'test'      ) {        console[console.info ? 'info' : 'log'](          'Download the Vue Devtools extension for a better development experience:\n' +          'https://github.com/vuejs/vue-devtools'        )      }    }    if (process.env.NODE_ENV !== 'production' &&      process.env.NODE_ENV !== 'test' &&      config.productionTip !== false &&      typeof console !== 'undefined'    ) {      console[console.info ? 'info' : 'log'](        `You are running Vue in development mode.\n` +        `Make sure to turn on production mode when deploying for production.\n` +        `See more tips at https://vuejs.org/guide/deployment.html`      )    }  }, 0)}export default Vue

主要是对Vue.config的扩展,在Vue.proptotype上挂载了$mount_patch_方法。

分析最后一个文件

src\platforms\web\entry-runtime-with-compiler.js

 {  const el = query(id)  return el && el.innerHTML})// mount 缓存原理的$mount方法const mount = Vue.prototype.$mount// 重写$mount方法Vue.prototype.$mount = function (  el?: string | Element,  hydrating?: boolean): Component {  el = el && query(el)  /* istanbul ignore if */  if (el === document.body || el === document.documentElement) {    process.env.NODE_ENV !== 'production' && warn(      `Do not mount Vue to  or  - mount to normal elements instead.`    )    return this  }  const options = this.$options  // resolve template/el and convert to render function  if (!options.render) {    let template = options.template    if (template) {      if (typeof template === 'string') {        if (template.charAt(0) === '#') {          template = idToTemplate(template)          /* istanbul ignore if */          if (process.env.NODE_ENV !== 'production' && !template) {            warn(              `Template element not found or is empty: ${options.template}`,              this            )          }        }      } else if (template.nodeType) {        template = template.innerHTML      } else {        if (process.env.NODE_ENV !== 'production') {          warn('invalid template option:' + template, this)        }        return this      }    } else if (el) {      template = getOuterHTML(el)    }    if (template) {      /* istanbul ignore if */      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {        mark('compile')      }      const { render, staticRenderFns } = compileToFunctions(template, {        outputSourceRange: process.env.NODE_ENV !== 'production',        shouldDecodeNewlines,        shouldDecodeNewlinesForHref,        delimiters: options.delimiters,        comments: options.comments      }, this)      options.render = render      options.staticRenderFns = staticRenderFns      /* istanbul ignore if */      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {        mark('compile end')        measure(`vue ${this._name} compile`, 'compile', 'compile end')      }    }  }  return mount.call(this, el, hydrating)}/** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */function getOuterHTML (el: Element): string {  if (el.outerHTML) {    return el.outerHTML  } else {    const container = document.createElement('div')    container.appendChild(el.cloneNode(true))    return container.innerHTML  }}// 挂载编译器compileVue.compile = compileToFunctionsexport default Vue

上面其实也就做了3件事情

  1. 缓存原来的$mount方法(因为后面$mount会被重写且使用到)
  2. 重写Vue.prototype上的$mount方法
  3. 在Vue上挂载compile

结果

经过上面的步骤,VueVue.prototype的结果如下


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

鲜花

握手

雷人

路过

鸡蛋

最新评论

返回顶部