vue源码解析—computed原理

本文详细介绍了Vue中computed的初始化过程,包括创建watcher和computedGetter,以及在组件挂载时如何触发计算和依赖绑定。当data变化时,如何通知computed进行更新,并详细阐述了这一过程中的依赖管理和异步更新机制。
摘要由CSDN通过智能技术生成


阅读本文前题是,已经对vue数据绑定机制中的的observer和watcher原理有个大致的了解,只要知道一个watcher去get一个data时,就会建立一个互相绑定的关系,data的会把watcher存人dep.subs数组,知道都有谁在watch它,以便发生变化时通知,而watcher也会把data的dep放入自己的deps数据,知道自己依赖哪些数据。

在此基础上,本文进一步讲解一下computed的原理,整体流程图如下,可对照此图理解后面的内容:

在这里插入图片描述

1. computed初始化

在初始化组件创建组件实例时,会调用到initComputed函数,这里会初始化组件里定义的computed属性,代码如下:

// vue/src/core/instance/state.js
const computedWatcherOptions = {
    lazy: true }

function initComputed (vm: Component, computed: Object) {
   
  // $flow-disable-line
  const watchers = vm._computedWatchers = Object.create(null)
  // computed properties are just getters during SSR
  const isSSR = isServerRendering()

  for (const key in computed) {
   
    const userDef = computed[key]
    const getter = typeof userDef === 'function' ? userDef : userDef.get
    if (process.env.NODE_ENV !== 'production' && getter == null) {
   
      warn(
        `Getter is missing for computed property "${
     key}".`,
        vm
      )
    }

    if (!isSSR) {
   
      // create internal watcher for the computed property.
      watchers[key] = new Watcher(
        vm,
        getter || noop,
        noop,
        computedWatcherOptions
      )
    }
    
    // component-defined computed properties are already defined on the
    // component prototype. We only need to define computed properties defined
    // at instantiation here.
    if (!(key in vm)) {
   
      defineComputed(vm, key, userDef)
    } else if (process.env.NODE_ENV !== 'production') {
   
      if (key in vm.$data) {
   
        warn(`The computed property "${
     key}" is already defined in data.`, vm)
      } else if (vm.$options.props && key in vm.$options
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值