Vue.js源码解析(第一期)

使用vue也有一段时间了,前段时间终于有时间看vue中内部实现的源码,阅读的过程中可以了解到对于某个功能的整体实现。以下是我对于源码的一些理解,欢迎指正。

1.Vue.js事件机制

Vue.js提供了四个时间API,分别是$on,$once,$of,$emit.

$on

$on方法用来在vm实例上监听一个自定义事件,该事件可用$emit触发。

  Vue.prototype.$on = function (event: string | Array<string>, fn: Function): Component {
    const vm: Component = this
   /*判断类型,如果是数组,则递归$on,为每一个成员都绑定方法*/
    if (Array.isArray(event)) {
      for (let i = 0, l = event.length; i < l; i++) {
        vm.$on(event[i], fn)
      }
    } else {
      (vm._events[event] || (vm._events[event] = [])).push(fn)
      // optimize hook:event cost by using a boolean flag marked at registration
      // instead of a hash lookup
  /*标记bool值来表明是否存在钩子,而不需要通过哈希表的方法来查找是否有钩子,这样做可以减少不必要的开销,
优化性能*/      if (hookRE.test(event)) {
        vm._hasHookEvent = true
      }
    }
    return vm
  }

$once

$once监听一个只能触发一次的事件,在触发以后会自动移除该事件。

  Vue.prototype.$once = function (event: string, fn: Function): Component {
    const vm: Component = this
    function on () {
  /*在第一次执行的时候移除该事件*/  
    vm.$off(event, on)
      fn.apply(vm, arguments)
    }
    on.fn = fn
  /*监听事件*/ 
   vm.$on(event, on)
    return vm
  }

$off

$off用来移除自定义事件

  Vue.prototype.$off = function (event?: string | Array<string>, fn?: Function): Component {
    const vm: Component = this
    /*如果不传参数的话注销所有事件*/
    if (!arguments.length) {
      vm._events = Object.create(null)
      return vm
    }
    // array of events
  /*如果是数组的话则递归移除所有的事件*/    if (Array.isArray(event)) {
      for (let i = 0, l = event.length; i < l; i++) {
        vm.$off(event[i], fn)
      }
      return vm
    }
    // specific event
    const cbs = vm._events[event]
    if (!cbs) {
      return vm
    }
    if (!fn) {
      vm._events[event] = null
      return vm
    }
    // specific handler
    let cb
    let i = cbs.length
    while (i--) {
      cb = cbs[i]
      if (cb === fn || cb.fn === fn) {
        cbs.splice(i, 1)
        break
      }
    }
    return vm
  }

$emit

$emit用来触发指定的自定义事件

   Vue.prototype.$emit = function (event: string): Component {   
  Vue.prototype.$emit = function (event: string): Component {
    const vm: Component = this
    if (process.env.NODE_ENV !== 'production') {
      const lowerCaseEvent = event.toLowerCase()
      if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
        tip(
          `Event "${lowerCaseEvent}" is emitted in component ` +
          `${formatComponentName(vm)} but the handler is registered for "${event}". ` +
          `Note that HTML attributes are case-insensitive and you cannot use ` +
          `v-on to listen to camelCase events when using in-DOM templates. ` +
          `You should probably use "${hyphenate(event)}" instead of "${event}".`
        )
      }
    }
    let cbs = vm._events[event]
    if (cbs) {
      cbs = cbs.length > 1 ? toArray(cbs) : cbs
      const args = toArray(arguments, 1)
      const info = `event handler for "${event}"`
      for (let i = 0, l = cbs.length; i < l; i++) {
        invokeWithErrorHandling(cbs[i], vm, args, vm, info)
      }
    }
    return vm
  }
}

2.keep-alive

keep-alive是Vue提供的一个抽象组件,用来对组件进行缓存,从而节省性能,由于是一个抽象组件,所以在页面渲染完毕后不会被渲染成一个DOM元素,也不会出现在父组件链中。

包含include和exclude属性,允许自定义组件是否缓存。

使用案例:

<keep-alive>

    <componet></component>

</keep-alive>

这样的话componet组件会被缓存。

props

keep-alive组件提供了include与exclude两个属性来允许组件有条件地进行缓存,二者都可以用逗号分隔字符串、正则表达式或一个数组来表示。

例如:

<keep-alive include="aLists,bLists">
      <router-view></router-view>
</keep-alive>
<keep-alive exclude="cLists">
      <router-view></router-view>
</keep-alive>

include属性表示只有name属性为alist是,blists组件会被缓存,(注意是组件的名字,不是路由的名字)其它组件不会被缓存exclude属性表示除了name属性为cLists的组件不会被缓存,其它组件都会被缓存。

生命周期

keep-alive提供了两个钩子,分别为activated与deactivated。

因为keep-alive将组件保存在内存中,并不会进行再次的销毁和重建,所以不会重新调用组件的比如created等生命周期方法,需要使用activated与deactivated来判断组件的活动状态。

小插曲:

之前做一个项目,在对首页页面缓存了之后把首页广告轮播图也缓存了,导致轮播图不能自动轮播,要想重新触发轮播图的轮播,只能在activated中进行操作。

源码实现

created和destroy

created () {
/*创建缓存对象*/
 this.keys = []
  },

  destroyed () {
/*销毁cache中所有的组价实例*/    for (const key in this.cache) {
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },

render

render () {
    /* 得到slot插槽中的第一个组件 */
    const vnode: VNode = getFirstComponentChild(this.$slots.default)

    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
        // check pattern
        /* 获取组件名称,优先获取组件的name字段,否则是组件的tag */
        const name: ?string = getComponentName(componentOptions)
        /* name不在inlcude中或者在exlude中则直接返回vnode(没有取缓存) */
        if (name && (
        (this.include && !matches(this.include, name)) ||
        (this.exclude && matches(this.exclude, name))
        )) {
            return vnode
        }
        const key: ?string = vnode.key == null
        // same constructor may get registered as different local components
        // so cid alone is not enough (#3269)
        ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
        : vnode.key
        /* 如果已经做过缓存了则直接从缓存中获取组件实例给vnode,还未缓存过则进行缓存 */
        if (this.cache[key]) {
            vnode.componentInstance = this.cache[key].componentInstance
        } else {
            this.cache[key] = vnode
        }
        /* keepAlive标记位 */
        vnode.data.keepAlive = true
    }
    return vnode
}

watch

用watch来监听pruneCache属性的变化,在改变的时候修改cache缓存中的缓存数据。

watch: {
    /* include和exclude进行监听,监听到修改的时候对cache进行修正*/
    include (val: string | RegExp) {
        pruneCache(this.cache, this._vnode, name => matches(val, name))
    },
    exclude (val: string | RegExp) {
        pruneCache(this.cache, this._vnode, name => !matches(val, name))
    }
},

遍历cache,不符合filter指定规则的话执行pruneCacheEntry进行销毁。其中pruneCacheEntry会调用组价实例的$destory方法来将组件销毁。

3.响应式原理

Vue.js的响应式原理依赖Object.defineProperty,在Vue3的版本之后使用Proxy,具体两者之间的区别小伙伴门可以自行百度一番。

将数据data变成可观察(observable)

function observe(value, cb) {
    Object.keys(value).forEach((key) => defineReactive(value, key, value[key] , cb))
}

function defineReactive (obj, key, val, cb) {
    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get: ()=>{
            /*....依赖收集等....*/
            /*Github:https://github.com/answershuto*/
            return val
        },
/*数据发生变化时触发set*/  set:newVal=> {
            val = newVal;
            cb();/*订阅者收到消息的回调*/
        }
}

class Vue {
    constructor(options) {
        this._data = options.data;
        observe(this._data, options.render)
    }
}

let app = new Vue({
    el: '#app',
    data: {
        text: 'text',
        text2: 'text2'
    },
    render(){
        console.log("render");
    }
})

代理

需要对app.data.text进行数据操作才会触发set,为了方便,我们可以在Vue的构造函数中为data执行一个代理proxy,这样可以把data的属性代理到vm实例上,我们可以直接通过app.text直接设置就能触发set对视图的更新。

_proxy.call(this, options.data);/*构造函数中*/

/*代理*/
function _proxy (data) {
    const that = this;
    Object.keys(data).forEach(key => {
        Object.defineProperty(that, key, {
            configurable: true,
            enumerable: true,
            get: function proxyGetter () {
                return that._data[key];
            },
            set: function proxySetter (val) {
                that._data[key] = val;
            }
        })
    });
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值