Vue中computed分析

前端开发 作者: 2024-08-21 16:15:01
Vue中computed分析 在Vue中computed是计算属性,其会根据所依赖的数据动态显示新的计算结果,虽然使用{{}}模板内的表达式非常便利,但是设计它们的初衷是用于简单运算的,在模板中放入太

Vue中computed分析

<!DOCTYPE html>
<html>
<head>
    <title>Vue</title>
</head>
<body>
    <div id="app"></div>
</body>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
        el: "#app",data: {
            a: 1,b: 2
        },template:`
            <div>
                <div>{{multiplication}}</div>
                <div>{{multiplication}}</div>
                <div>{{multiplication}}</div>
                <div>{{multiplicationArrow}}</div>
                <button @click="updateSetting">updateSetting</button>
            </div>
        `,computed:{
            multiplication: function(){
                console.log("a * b"); // 初始只打印一次 返回值被缓存
                return this.a * this.b;
            },multiplicationArrow: vm => vm.a * vm.b * 3,// 箭头函数可以通过传入的参数获取当前实例
            setting: {
                get: function(){
                    console.log("a * b * 6");
                    return this.a * this.b * 6;
                },set: function(v){
                    console.log(`${v} -> a`);
                    this.a = v;
                }
            }
        },methods:{
            updateSetting: function(){ // 点击按钮后
                console.log(this.setting); // 12
                this.setting = 3; // 3 -> a
                console.log(this.setting); // 36
            }
        },})
</script>
</html>
  • Observer: 这里的主要工作是递归地监听对象上的所有属性,在属性值改变的时候,触发相应的Watcher
  • Watcher: 观察者,当监听的数据值修改时,执行响应的回调函数,在Vue里面的更新模板内容。
  • Dep: 链接ObserverWatcher的桥梁,每一个Observer对应一个Dep,它内部维护一个数组,保存与该Observer相关的Watcher
// dev/src/core/instance/state.js line 47
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) // 定义computed属性则进行初始化
  if (opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm,opts.watch)
  }
}

// dev/src/core/instance/state.js line 169
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] // 获取计算属性的key值定义
    const getter = typeof userDef === 'function' ? userDef : userDef.get // 由于计算属性接受两种类型的参数 此处判断用以获取getter
    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.
      // 生成computed watcher(vm,getter,noop,{ lazy: true })
      watchers[key] = new Watcher( // 计算属性创建观察者watcher和消息订阅器dep
        vm,getter || 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.props) {
        warn(`The computed property "${key}" is already defined as a prop.`,vm)
      }
    }
  }
}
// dev/src/core/instance/state.js line 31
const sharedPropertyDefinition = {
  enumerable: true,configurable: true,get: noop,set: noop
}

// dev/src/core/instance/state.js line 210
export function defineComputed (
  target: any,key: string,userDef: Object | Function
) {
  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
  }
  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
      )
    }
  }
  Object.defineProperty(target,sharedPropertyDefinition)
}

/**
 经过重写之后的属性描述符在某条件分支大致呈现如下
 sharedPropertyDefinition = {
    enumerable: true,get: function computedGetter () {
      const watcher = this._computedWatchers && this._computedWatchers[key]
      if (watcher) {
        if (watcher.dirty) {
          watcher.evaluate()
        }
        if (Dep.target) {
          watcher.depend()
        }
        return watcher.value
      }
    },set: userDef.set || noop
 } 
 当计算属性被调用时便会执行 get 访问函数,从而关联上观察者对象 watcher 然后执行 wather.depend() 收集依赖和 watcher.evaluate() 计算求值。
*/
https://github.com/WindrunnerMax/EveryDay
https://cn.vuejs.org/v2/api/#computed
https://juejin.im/post/6844903678533451783
https://juejin.im/post/6844903873925087239
https://cn.vuejs.org/v2/guide/computed.html
https://zheyaoa.github.io/2019/09/07/computed/
https://www.cnblogs.com/tugenhua0707/p/11760466.html
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_66179.html
Vue中computed分析