资讯专栏INFORMATION COLUMN

Vue 1.0.28 源码解析

URLOS / 1357人阅读

摘要:整体概览源码最终是向外部抛出一个的构造函数,见源码在源码最开始,通过方法见源码向构造函数添加全局方法,如等,主要初始化一些全局使用的方法变量和配置实例化当使用时,最基本使用方式如下此时,会调用构造函数实例化一个对象,而在构造函数中只有这句代

整体概览

Vue源码最终是向外部抛出一个Vue的构造函数,见源码:

</>复制代码

  1. function Vue (options) {
  2. this._init(options)
  3. }

在源码最开始,通过installGlobalAPI方法(见源码)向Vue构造函数添加全局方法,如Vue.extend、Vue.nextTick、Vue.delete等,主要初始化Vue一些全局使用的方法、变量和配置;

</>复制代码

  1. export default function (Vue){
  2. Vue.options = {
  3. .....
  4. }
  5. Vue.extend = function (extendOptions){
  6. ......
  7. }
  8. Vue.use = function (plugin){
  9. ......
  10. }
  11. Vue.mixin = function (mixin){
  12. ......
  13. }
  14. Vue.extend = function (extendOptions){
  15. ......
  16. }
  17. }
实例化Vue

当使用vue时,最基本使用方式如下:

</>复制代码

  1. var app = new Vue({
  2. el: "#app",
  3. data: {
  4. message: "Hello Vue!"
  5. }
  6. })

此时,会调用构造函数实例化一个vue对象,而在构造函数中只有这句代码this.init(options);而在init中(源码),主要进行一些变量的初始化、option重组、各种状态、事件初始化;如下:

</>复制代码

  1. Vue.prototype._init = function (options) {
  2. options = options || {}
  3. this.$el = null
  4. this.$parent = options.parent
  5. this.$root = this.$parent
  6. ? this.$parent.$root
  7. : this
  8. this.$children = []
  9. this.$refs = {} // child vm references
  10. this.$els = {} // element references
  11. this._watchers = [] // all watchers as an array
  12. this._directives = [] // all directives
  13. ...... // 更多见源码
  14. options = this.$options = mergeOptions(
  15. this.constructor.options,
  16. options,
  17. this
  18. )
  19. // set ref
  20. this._updateRef()
  21. // initialize data as empty object.
  22. // it will be filled up in _initData().
  23. this._data = {}
  24. // call init hook
  25. this._callHook("init")
  26. // initialize data observation and scope inheritance.
  27. this._initState()
  28. // setup event system and option events.
  29. this._initEvents()
  30. // call created hook
  31. this._callHook("created")
  32. // if `el` option is passed, start compilation.
  33. if (options.el) {
  34. this.$mount(options.el)
  35. }
  36. }

在其中通过mergeOptions方法,将全局this.constructor.options与传入的options及实例化的对象进行合并;而this.constructor.options则是上面初始化vue时进行配置的,其中主要包括一些全局使用的指令、过滤器,如经常使用的"v-if"、"v-for"、"v-show"、"currency":

</>复制代码

  1. this.constructor.options = {
  2. directives: {
  3. bind: {}, // v-bind
  4. cloak: {}, // v-cloak
  5. el: {}, // v-el
  6. for: {}, // v-for
  7. html: {}, // v-html
  8. if: {}, // v-if
  9. for: {}, // v-for
  10. text: {}, // v-text
  11. model: {}, // v-model
  12. on: {}, // v-on
  13. show: {} // v-show
  14. },
  15. elementDirectives: {
  16. partial: {}, // api: https://v1.vuejs.org/api/#partial
  17. slot: {} //
  18. },
  19. filters: { // api: https://v1.vuejs.org/api/#Filters
  20. capitalize: function() {}, // {{ msg | capitalize }} ‘abc’ => ‘Abc’
  21. currency: funnction() {},
  22. debounce: function() {},
  23. filterBy: function() {},
  24. json: function() {},
  25. limitBy: function() {},
  26. lowercase: function() {},
  27. orderBy: function() {},
  28. pluralize: function() {},
  29. uppercase: function() {}
  30. }
  31. }

然后,会触发初始化一些状态、事件、触发init、create钩子;然后随后,会触发this.$mount(options.el);进行实例挂载,将dom添加到页面;而this.$mount()方法则包含了绝大部分页面渲染的代码量,包括模板的嵌入、编译、link、指令和watcher的生成、批处理的执行等等,后续会详细进行说明;

_compile函数之transclude

在上面说了下,在Vue.prototype.$mount完成了大部分工作,而在$mount方法里面,最主要的工作量由this._compile(el)承担;其主要包括transclude(嵌入)、compileRoot(根节点编译)、compile(页面其他的编译);而在这儿主要说明transclude方法;

通过对transclude进行网络翻译结果是"嵌入";其主要目的是将页面中自定义的节点转化为真实的html节点;如一个组件其实际dom为

hello {{message}}

,源码; 当我们使用时
; 会通过transclude将其转化为

hello {{message}}

,见源码注释;

那transclude具体干了什么呢,我们先看它的源码:

</>复制代码

  1. export function transclude (el, options) {
  2. // extract container attributes to pass them down
  3. // to compiler, because they need to be compiled in
  4. // parent scope. we are mutating the options object here
  5. // assuming the same object will be used for compile
  6. // right after this.
  7. if (options) {
  8. // 把el(虚拟节点,如)元素上的所有attributes抽取出来存放在了选项对象的_containerAttrs属性上
  9. // 使用el.attributes 方法获取el上面,并使用toArray方法,将类数组转换为真实数组
  10. options._containerAttrs = extractAttrs(el)
  11. }
  12. // for template tags, what we want is its content as
  13. // a documentFragment (for fragment instances)
  14. // 判断是否为 template 标签
  15. if (isTemplate(el)) {
  16. // 得到一段存放在documentFragment里的真实dom
  17. el = parseTemplate(el)
  18. }
  19. if (options) {
  20. if (options._asComponent && !options.template) {
  21. options.template = ""
  22. }
  23. if (options.template) {
  24. // 将el的内容(子元素和文本节点)抽取出来
  25. options._content = extractContent(el)
  26. // 使用options.template 将虚拟节点转化为真实html, =>

    hello {{ msg }}

  27. // 但不包括未绑定数据, 则上面转化为 =>

    hello

  28. el = transcludeTemplate(el, options)
  29. }
  30. }
  31. // isFragment: node is a DocumentFragment
  32. // 使用nodeType 为 11 进行判断是非为文档片段
  33. if (isFragment(el)) {
  34. // anchors for fragment instance
  35. // passing in `persist: true` to avoid them being
  36. // discarded by IE during template cloning
  37. prepend(createAnchor("v-start", true), el)
  38. el.appendChild(createAnchor("v-end", true))
  39. }
  40. return el
  41. }

首先先看如下代码:

</>复制代码

  1. if (options) {
  2. // 把el(虚拟节点,如)元素上的所有attributes抽取出来存放在了选项对象的_containerAttrs属性上
  3. // 使用el.attributes 方法获取el上面,并使用toArray方法,将类数组转换为真实数组
  4. options._containerAttrs = extractAttrs(el)
  5. }

而extractAttrs方法如下,其主要根据元素nodeType去判断是否为元素节点,如果为元素节点,且元素有相关属性,则将属性值取出之后,再转为属性数组;最后将属性数组放到options._containerAttrs中,为什么要这么做呢?因为现在的el可能不是真实的元素,而是诸如,在后面编译过程,需要将其替换为真实的html节点,所以,它上面的属性值都会先取出来预存起来,后面合并到真实html根节点的属性上面;

</>复制代码

  1. function extractAttrs (el) {
  2. // 只查找元素节点及有属性
  3. if (el.nodeType === 1 && el.hasAttributes()) {
  4. // attributes 属性返回指定节点的属性集合,即 NamedNodeMap, 类数组
  5. return toArray(el.attributes)
  6. }
  7. }

下一句,根据元素nodeName是否为“template”去判断是否为元素;如果是,则走parseTemplate(el)方法,并覆盖当前el对象

</>复制代码

  1. if (isTemplate(el)) {
  2. // 得到一段存放在documentFragment里的真实dom
  3. el = parseTemplate(el)
  4. }
  5. function isTemplate (el) {
  6. return el.tagName &&
  7. el.tagName.toLowerCase() === "template"
  8. }

parseTemplate则主要是将传入内容生成一段存放在documentFragment里的真实dom;进入函数,首先判断传入是否已经是一个文档片段,如果已经是,则直接返回;否则,判断传入是否为字符串,如果为字符串, 先判断是否是"#test"这种选择器类型,如果是,通过document.getElementById方法取出元素,如果文档中有此元素,将通过nodeToFragment方式,将其放入一个新的节点片段中并赋给frag,最后返回到外面;如果不是选择器类型字符串,则使用stringToFragment将其生成一个新的节点片段,并返回;如果传入非字符串而是节点(不管是什么节点,可以是元素节点、文本节点、甚至Comment节点等);则直接通过nodeToFragment生成节点片段并返回;

</>复制代码

  1. export function parseTemplate (template, shouldClone, raw) {
  2. var node, frag
  3. // if the template is already a document fragment,
  4. // do nothing
  5. // 是否为文档片段, nodetype是否为11
  6. // https://developer.mozilla.org/zh-CN/docs/Web/API/DocumentFragment
  7. // 判断传入是否已经是一个文档片段,如果已经是,则直接返回
  8. if (isFragment(template)) {
  9. trimNode(template)
  10. return shouldClone
  11. ? cloneNode(template)
  12. : template
  13. }
  14. // 判断传入是否为字符串
  15. if (typeof template === "string") {
  16. // id selector
  17. if (!raw && template.charAt(0) === "#") {
  18. // id selector can be cached too
  19. frag = idSelectorCache.get(template)
  20. if (!frag) {
  21. node = document.getElementById(template.slice(1))
  22. if (node) {
  23. frag = nodeToFragment(node)
  24. // save selector to cache
  25. idSelectorCache.put(template, frag)
  26. }
  27. }
  28. } else {
  29. // normal string template
  30. frag = stringToFragment(template, raw)
  31. }
  32. } else if (template.nodeType) {
  33. // a direct node
  34. frag = nodeToFragment(template)
  35. }
  36. return frag && shouldClone
  37. ? cloneNode(frag)
  38. : frag
  39. }

从上面可见,在parseTemplate里面最重要的是nodeToFragment和stringToFragment;那么,它们又是如何将传入内容转化为新的文档片段呢?首先看nodeToFragment:

</>复制代码

  1. function nodeToFragment (node) {
  2. // if its a template tag and the browser supports it,
  3. // its content is already a document fragment. However, iOS Safari has
  4. // bug when using directly cloned template content with touch
  5. // events and can cause crashes when the nodes are removed from DOM, so we
  6. // have to treat template elements as string templates. (#2805)
  7. /* istanbul ignore if */
  8. // 是template元素或者documentFragment,使用stringToFragment转化并保存节点内容
  9. if (isRealTemplate(node)) {
  10. return stringToFragment(node.innerHTML)
  11. }
  12. // script template
  13. if (node.tagName === "SCRIPT") {
  14. return stringToFragment(node.textContent)
  15. }
  16. // normal node, clone it to avoid mutating the original
  17. var clonedNode = cloneNode(node)
  18. var frag = document.createDocumentFragment()
  19. var child
  20. /* eslint-disable no-cond-assign */
  21. while (child = clonedNode.firstChild) {
  22. /* eslint-enable no-cond-assign */
  23. frag.appendChild(child)
  24. }
  25. trimNode(frag)
  26. return frag
  27. }

其实看源码,很容易理解,首先判断传入内容是否为template元素或者documentFragment或者script标签,如果是,都直接走stringToFragment;后面就是先使用document.createDocumentFragment创建一个文档片段,然后将节点进行循环appendChild到创建的文档片段中,并返回新的片段;
那么,stringToFragment呢?这个就相对复杂一点了,如下:

</>复制代码

  1. function stringToFragment (templateString, raw) {
  2. // try a cache hit first
  3. var cacheKey = raw
  4. ? templateString
  5. : templateString.trim() //trim() 方法会从一个字符串的两端删除空白字符
  6. var hit = templateCache.get(cacheKey)
  7. if (hit) {
  8. return hit
  9. }
  10. // 创建一个文档片段
  11. var frag = document.createDocumentFragment()
  12. // tagRE: /<([w:-]+)/
  13. // 匹配标签
  14. // "".match(/<([w:-]+)/) => [""]
  15. var tagMatch = templateString.match(tagRE)
  16. // entityRE: /&#?w+?;/
  17. var entityMatch = entityRE.test(templateString)
  18. // commentRE: /

它对应的descriptor就是:

</>复制代码

  1. descriptor = {
  2. arg: undefined,
  3. attr: "v-demo",
  4. def: {
  5. bind: function() {}, // 上面定义的bind
  6. update: function() {} // 上面定义的update
  7. },
  8. expression:"demo",
  9. filters: undefined,
  10. modifiers: {},
  11. name: "demo"
  12. }

接着上面的,使用extend(this, def)就将def中定义的方法或属性就复制到实例化指令对象上面;好供后面使用;

</>复制代码

  1. // initial bind
  2. if (this.bind) {
  3. this.bind()
  4. }

这就是执行上面刚刚保存的bind方法;当执行此方法时,上面就会执行

</>复制代码

  1. this.el.setAttribute("style", "color: green");

将字体颜色改为绿色;

</>复制代码

  1. // 下面这些判断是因为许多指令比如slot component之类的并不是响应式的,
  2. // 他们只需要在bind里处理好dom的分发和编译/link即可然后他们的使命就结束了,生成watcher和收集依赖等步骤根本没有
  3. // 所以根本不用执行下面的处理
  4. if (this.literal) {
  5. } else if (
  6. (this.expression || this.modifiers) &&
  7. (this.update || this.twoWay) &&
  8. !this._checkStatement()
  9. ) {
  10. var watcher = this._watcher = new Watcher(
  11. this.vm,
  12. this.expression,
  13. this._update, // callback
  14. {
  15. filters: this.filters,
  16. twoWay: this.twoWay,
  17. deep: this.deep,
  18. preProcess: preProcess,
  19. postProcess: postProcess,
  20. scope: this._scope
  21. }
  22. )
  23. }

而这儿就是对需要添加双向绑定的指令添加watcher;对应watcher后面再进行详细说明; 可以从上看出,传入了this._update方法,其实也就是当数据变化时,就会执行this._update方法,而:

</>复制代码

  1. var dir = this
  2. if (this.update) {
  3. // 处理一下原本的update函数,加入lock判断
  4. this._update = function (val, oldVal) {
  5. if (!dir._locked) {
  6. dir.update(val, oldVal)
  7. }
  8. }
  9. } else {
  10. this._update = function() {}
  11. }

其实也就是执行上面的descriptor.def.update方法,所以当值变化时,会触发我们自定义指令时定义的update方法,而发生颜色变化;

这是指令最主要的代码部分;其他的如下:

</>复制代码

  1. // 获取指令的参数, 对于一些指令, 指令的元素上可能存在其他的attr来作为指令运行的参数
  2. // 比如v-for指令,那么元素上的attr: track-by="..." 就是参数
  3. // 比如组件指令,那么元素上可能写了transition-mode="out-in", 诸如此类
  4. this._setupParams();
  5. // 当一个指令需要销毁时,对其进行销毁处理;此时,如果定义了unbind方法,也会在此刻调用
  6. this._teardown();
  7. 而对于每个指令的处理原理,可以看其对应源码;如v-show源码:
  8. // src/directives/public/show.js
  9. import { getAttr, inDoc } from "../../util/index"
  10. import { applyTransition } from "../../transition/index"
  11. export default {
  12. bind () {
  13. // check else block
  14. var next = this.el.nextElementSibling
  15. if (next && getAttr(next, "v-else") !== null) {
  16. this.elseEl = next
  17. }
  18. },
  19. update (value) {
  20. this.apply(this.el, value)
  21. if (this.elseEl) {
  22. this.apply(this.elseEl, !value)
  23. }
  24. },
  25. apply (el, value) {
  26. if (inDoc(el)) {
  27. applyTransition(el, value ? 1 : -1, toggle, this.vm)
  28. } else {
  29. toggle()
  30. }
  31. function toggle () {
  32. el.style.display = value ? "" : "none"
  33. }
  34. }
  35. }

可以从上面看出在初始化页面绑定时,主要获取后面兄弟元素是否使用v-else; 如果使用,将元素保存到this.elseEl中,而当值变化执行update时,主要执行了this.apply;而最终只是执行了下面代码:

</>复制代码

  1. el.style.display = value ? "" : "none"

从而达到隐藏或者展示元素的效果;

未完待续,后续会持续完善......

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/93224.html

相关文章

  • JavaScript 进阶之深入理解数据双向绑定

    摘要:当我们的视图和数据任何一方发生变化的时候,我们希望能够通知对方也更新,这就是所谓的数据双向绑定。返回值返回传入函数的对象,即第一个参数该方法重点是描述,对象里目前存在的属性描述符有两种主要形式数据描述符和存取描述符。 前言 谈起当前前端最热门的 js 框架,必少不了 Vue、React、Angular,对于大多数人来说,我们更多的是在使用框架,对于框架解决痛点背后使用的基本原理往往关注...

    sarva 评论0 收藏0
  • vue-loader 源码解析系列之 selector

    摘要:当前正在处理的节点,以及该节点的和等信息。源码解析之一整体分析源码解析之三写作中源码解析之四写作中作者博客作者作者微博 笔者系 vue-loader 贡献者之一(#16) 前言 vue-loader 源码解析系列之一,阅读该文章之前,请大家首先参考大纲 vue-loader 源码解析系列之 整体分析 selector 做了什么 const path = require(path) co...

    miqt 评论0 收藏0
  • Vue源码解析:AST语法树转render函数

    摘要:源码解析这边解析的是从树转换成函数部分的源码,由于第一次提交的源码这部分不全,故做了部分更新,代码全在文件夹中。入口整个语法树转函数的起点是文件中的函数明显看到,函数传入参数为语法树,内部调用函数开始解析根节点容器节点。 通过对 Vue2.0 源码阅读,想写一写自己的理解,能力有限故从尤大佬2016.4.11第一次提交开始读,准备陆续写: 模版字符串转AST语法树 AST语法树转r...

    trilever 评论0 收藏0
  • Vue源码解析:AST语法树转render函数

    摘要:源码解析这边解析的是从树转换成函数部分的源码,由于第一次提交的源码这部分不全,故做了部分更新,代码全在文件夹中。入口整个语法树转函数的起点是文件中的函数明显看到,函数传入参数为语法树,内部调用函数开始解析根节点容器节点。 通过对 Vue2.0 源码阅读,想写一写自己的理解,能力有限故从尤大佬2016.4.11第一次提交开始读,准备陆续写: 模版字符串转AST语法树 AST语法树转r...

    Karuru 评论0 收藏0

发表评论

0条评论

URLOS

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<