深入理解 Vue 中的 Computed

本文深入探讨 Vue 中的 Computed 计算属性,揭示其内部如何通过 lazy watcher 实现。计算属性在初始化时创建 watcher 对象并订阅依赖变化,值变化时仅通过标识更新。对比 watch,computed 具有缓存特性,适用于多依赖计算,而 watch 适合执行异步操作和限制执行频率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

computed 实现的本质- lazy watcher

在 Vue 实例初始化过程中,在生命周期 beforeCreatecreated 之间,调用 initState 方法进行各属性的初始化(props、data、methods、computed、watch)

// /src/core/instance/init.js
export function initMixin (Vue: Class<Component>) {
   
  Vue.prototype._init = function (options?: Object) {
   
  ...
    initLifecycle(vm)
    initEvents(vm)
    initRender(vm)
    callHook(vm, 'beforeCreate')
    initInjections(vm) // resolve injections before data/props
    initState(vm)
    initProvide(vm) // resolve provide after data/props
    callHook(vm, 'created')
  ...
  }
}
// /src/core/instance/state.js
export function initState (vm: Component) {
   
  vm._watchers = []
  const opts = vm.$options
  if (opts.props) initProps(vm, opts.props)
  if (opts.methods) initMethods(vm, opts.methods)
  if (opts.data) {
   
    initData(vm)
  } else {
   
    observe(vm._data = {
   }, true /* asRootData */)
  }
  if (opts.computed) initComputed(vm, opts.computed)
  if (opts.watch && opts.watch !== nativeWatch) {
   
    initWatch(vm, opts.watch)
  }
}

而本文就 Vue 如何实现 Computed 计算属性做深入的分析,即查看 initComputed 中的具体是如何实现的。

// /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) {
   
     // userDef 存在两种情况
     // 一种是常见的定义为方法即该方法默认为get
     // 另外就是自定义get和set,故类型为对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值