computed的实现原理

介绍

官方文档

  1. 基于它的依赖进行缓存的,跟计算属性相关的数据发生了改变,计算属性就会重新计算,不相关的值发生变化,不会重新计算计算属性
  2. 根据已知data中的值,生成一个额外的新值,且新值会因data中的值变化而变化

computed和watch的区别

  1. watch擅长处理的场景:一个数据影响多个数据。是观察一个特定的值,当该值变化时执行特定的函数。
  2. computed擅长处理的场景:一个数据受多个数据影响。计算属性,是基于它的依赖缓存,只有相关依赖发生改变时才会重新取值。

初始化computed过程

源码

// vue 2.6.10
const sharedPropertyDefinition = {
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop
}

const computedWatcherOptions = { lazy: true }

function initComputed (vm: Component, computed: Object) {
  // 对computed中的属性生成唯一的watcher,并保存在vm._computedWatchers中
  const watchers = vm._computedWatchers = Object.create(null)

  // 计算属性在SSR环境下,只是一个普通的getter方法
  // isServerRendering返回一个布尔值判断是否是SSR环境
  const isSSR = isServerRendering()

  // 循环初始化每个计算属性,
  for (const key in computed) {
    const userDef = computed[key]
    // 判断用户提供的计算属性是否是函数,如果是函数,将这个函数当做getter使用,否则当做对象处理,使用对象的get方法
    const getter = typeof userDef === 'function' ? userDef : userDef.get
    // 如果计算属性不是函数,不是对象,或者提供了对象却没有get方法,则警告提示
    if (process.env.NODE_ENV !== 'production' && getter == null) {
      warn(
        `Getter is missing for computed property "${key}".`,
        vm
      )
    }

    // 在非isSSR环境下,为计算属性创建内部watchers
    if (!isSSR) {
      watchers[key] = new Watcher(
        vm,
        getter || noop,
        noop,
        computedWatcherOptions
      )
    }

    // 判断计算属性名是否已经存在vm中,如果不存在,则使用defineComputed函数在vm上设置一个计算属性
    // 如果存在,判断是否在data或props上重名,并打印警告
    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.props) {
        warn(`The computed property "${key}" is already defined as a prop.`, vm)
      }
    }
  }
}

export function defineComputed (
  target: any,
  key: string,
  userDef: Object | Function
) {
  // 是否应该有缓存,计算属性在SSR环境下,计算属性才有缓存
  const shouldCache = !isServerRendering()

  if (typeof userDef === 'function') {
    sharedPropertyDefinition.get = shouldCache
      ? createComputedGetter(key)
      : createGetterInvoker(userDef)
    sharedPropertyDefinition.set = noop
  } else {
    sharedPropertyDefinition.get = userDef.get
      ? shouldCache && userDef.cache !== false
        ? createComputedGetter(key)
        : createGetterInvoker(userDef.get)
      : noop
    sharedPropertyDefinition.set = userDef.set || noop
  }
  // 如果用户没有设置setter下,则为计算属性添加一个默认setter函数,并当函数执行时,打印警告
  if (process.env.NODE_ENV !== 'production' &&
      sharedPropertyDefinition.set === noop) {
    sharedPropertyDefinition.set = function () {
      warn(
        `Computed property "${key}" was assigned to but it has no setter.`,
        this
      )
    }
  }
  // 在target设置key属性,sharedPropertyDefinition为属性描述符
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

function createComputedGetter (key) {
  return function computedGetter () {
    // 通过key读取this._computedWatchers中的计算属性的watcher实例,赋值给watcher变量
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      // 如果该属性的watcher.dirty为true,则调用watcher.evaluate()方法重新计算,获取新的值
      if (watcher.dirty) {
        watcher.evaluate()
      }
      // 如果Dep.target存在,则调用watcher.depend()方法,将读取计算属性的watcher添加到
      // 计算属性所依赖的所有状态的依赖列表中
      if (Dep.target) {
        watcher.depend()
      }
      return watcher.value
    }
  }
}

// 使用该函数设置,计算属性就是个普通的getter方法,没有缓存。计算属性的watcher不会得到任何通知,
// 即:在SSR环境下生效
function createGetterInvoker(fn) {
  return function computedGetter () {
    return fn.call(this, this)
  }
}

与computed相关的watcher

源码

// 部分代码
export default class Watcher {
  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {

    if (options) {
      this.lazy = !!options.lazy // 来自computedWatcherOptions对象
    } else {
      this.lazy = false
    }
    this.dirty = this.lazy // for lazy watchers

    this.value = this.lazy
      ? undefined
      : this.get()
  }

  get () {
    // ...
  }

  update () {
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      // ...
    } else {
      // ...
    }
  }

  // 执行get方法重新计算一下值,然后将dirty设置为false,表示缓存已更新
  evaluate () {
    this.value = this.get()
    this.dirty = false
  }
  
  // 将组将的watcher加入到dep实例的依赖列表中,让组件的watcher观察计算属性中用到的状态的变化
  depend () {
    let i = this.deps.length
    while (i--) {
      this.deps[i].depend()
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值