vue3 computed计算属性(源码解析)

vue3 computed计算属性的灵活运用(源码解析)

  • 只要是对data中的数据做一些复杂处理的时候 用就完事了
  • 对数据进行复杂运算 可以将运算结果缓存(多地方使用 只执行一次) 节省资源
  • 避免多地方使用相同的逻辑导致 代码重复 会降低代码的可读性 和可维护性

computed使用

//使用方法1
computed:{
    
    
  handleName(){
    
    
    return this.name + this.number
  }
}
//使用方法2
methods:{
    
    
  setHandleName(){
    
    
    this.handleName="xxxxxxx"
  }
}
computed:{
    
    
  handleName:{
    
    
    get(){
    
    
      return this.name + this.number
    },
      //newValue  xxxxxxx
    set(newValue){
    
    
        //对newValue 做一些处理  茹改变data中的值
      }
  }
}

computed vu3 部分源码

//computed 源码
//从组件options中解构出来的 computed=> computedOptions
  if (computedOptions) {
    
    
    //循环computedOptions  从中拿到每个计算属性 并进行处理
    for (const key in computedOptions) {
    
    
      //将当前计算属性赋值给opt
      const opt = (computedOptions as ComputedOptions)[key]
      //判断 当前计算属性是否是一个方法  如果是  那么就将当前opt bind publicThis  如果不是  那么就是一个对象 将opt.get也bind上  publicThis并返回
      const get = isFunction(opt)? opt.bind(publicThis, publicThis): isFunction(opt.get)? opt.get.bind(publicThis, publicThis): NOOP
      //如果不是方法 也不是一个对象   那么就提示warn
      if (__DEV__ && get === NOOP) {
    
    
        warn(`Computed property "${
      
      key}" has no getter.`)
      }
      //再判断当前的set   道理同上
      const set =
        !isFunction(opt) && isFunction(opt.set)
          ? opt.set.bind(publicThis)
          : __DEV__
          ? () => {
    
    
              warn(
                `Write operation failed: computed property "${
      
      key}" is readonly.`
              )
            }
          : NOOP
      //将computed 的get set 属性加入响应式系统中
      const c = computed({
    
    get,set})
      Object.defineProperty(ctx, key, {
    
    
        enumerable: true,
        configurable: true,
        get: () => c.value,
        set: v => (c.value = v)
      })
      if (__DEV__) {
    
    
        checkDuplicateProperties!(OptionTypes.COMPUTED, key)
      }
    }
  }

猜你喜欢

转载自blog.csdn.net/qq_51075057/article/details/130723993
今日推荐