vue中watch和computed为什么能监听到数据的改变以及不同之处

先来个流程图,水平有限,凑活看吧-_-||

首先在创建一个Vue应用时:

var app = new Vue({
 el: '#app',
 data: {
  message: 'Hello Vue!'
 }
})

Vue构造函数源码:

//创建Vue构造函数
function Vue (options) {
 if (!(this instanceof Vue)
 ) {
  warn('Vue is a constructor and should be called with the `new` keyword');
 }
 this._init(options);
}
//_init方法,会初始化data,watch,computed等
Vue.prototype._init = function (options) {
 var vm = this;
 // a uid
 vm._uid = uid$3++;
 ......
 // expose real self
 vm._self = vm;
 initLifecycle(vm);
 initEvents(vm);
 initRender(vm);
 callHook(vm, 'beforeCreate');
 initInjections(vm); // resolve injections before data/props
 initState(vm);
 ......
};

在initState方法中会初始化data、watch和computed,并调用observe函数监听data(Object.defineProperty):

function initState (vm) {
 vm._watchers = [];
 var opts = vm.$options;
 if (opts.props) { initProps(vm, opts.props); }
 if (opts.methods) { initMethods(vm, opts.methods); }
 if (opts.data) {
  initData(vm);//initData中也会调用observe方法
 } else {
  observe(vm._data = {}, true /* asRootData */);
 }
 if (opts.computed) { initComputed(vm, opts.computed); }
 if (opts.watch && opts.watch !== nativeWatch) {
  initWatch(vm, opts.watch);
 }
}

1、observe

observe在initState 时被调用,为vue实例的data属性值创建getter、setter函数,在setter中dep.depend会把watcher实例添加到Dep实例的subs属性中,在getter中会调用dep.notify,调用watcher的update方法。

/**
 * Attempt to create an observer instance for a value,
 * returns the new observer if successfully observed,
 * or the existing observer if the value already has one.
 * 该函数在initState中有调用
 */
function observe (value, asRootData) {
 if (!isObject(value) || value instanceof VNode) {
  return
 }
 var ob;
 if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
  ob = value.__ob__;
 } else if (
  shouldObserve &&
  !isServerRendering() &&
  (Array.isArray(value) || isPlainObject(value)) &&
  Object.isExtensible(value) &&
  !value._isVue
 ) {
  ob = new Observer(value);
 }
 if (asRootData && ob) {
  ob.vmCount++;
 }
 re * Observer class that is attached to each observed
 * object. Once attached, the observer converts the target
 * object's property keys into getter/setters that
 * collect dependencies and dispatch updates.
 */
var Observer = function Observer (value) {
 this.value = value;
 this.dep = new Dep();
 this.vmCount = 0;
 def(value, '__ob__', this);
 if (Array.isArray(value)) {
  if (hasProto) {
   protoAugment(value, arrayMethods);
  } else {
   copyAugment(value, arrayMethods, arrayKeys);
  }
  this.observeArray(value);
 } else {
  this.walk(value);
 }
};
/**
 * Walk through all properties and convert them into
 * getter/setters. This method should only be called when
 * value type is Object.
 */
Observer.prototype.walk = function walk (obj) {
 var keys = Object.keys(obj);
 for (var i = 0; i < keys.length; i++) {
  defineReactive$$1(obj, keys[i]);
 }
};
/**
 * Define a reactive property on an Object.
 */
function defineReactive$$1 (
 obj,
 key,
 val,
 customSetter,
 shallow
) {
 var dep = new Dep();
 var property = Object.getOwnPropertyDescriptor(obj, key);
 if (property && property.configurable === false) {
  return
 }
 // cater for pre-defined getter/setters
 var getter = property && property.get;
 var setter = property && property.set;
 if ((!getter || setter) && arguments.length === 2) {
  val = obj[key];
 }
 var childOb = !shallow && observe(val);
 Object.defineProperty(obj, key, {
  enumerable: true,
  configurable: true,
  get: function reactiveGetter () {
   var value = getter ? getter.call(obj) : val;
    //Dep.target 全局变量指向的就是指向当前正在解析生成的 Watcher
    //会执行到dep.addSub,将Watcher添加到Dep对象的Watcher数组中
   if (Dep.target) {
    dep.depend();
    if (childOb) {
     childOb.dep.depend();
     if (Array.isArray(value)) {
      dependArray(value);
     }
    }
   }
   return value
  },
  set: function reactiveSetter (newVal) {
   var value = getter ? getter.call(obj) : val;
   /* eslint-disable no-self-compare */
   if (newVal === value || (newVal !== newVal && value !== value)) {
    return
   }
   /* eslint-enable no-self-compare */
   if (customSetter) {
    customSetter();
   }
   // #7981: for accessor properties without setter
   if (getter && !setter) { return }
   if (setter) {
    setter.call(obj, newVal);
   } else {
    val = newVal;
   }
   childOb = !shallow && observe(newVal);
   dep.notify();//如果数据被重新赋值了, 调用 Dep 的 notify 方法, 通知所有的 Watcher
 } }); }

2、Dep

Watcher的update方法是在new Dep的notify的方法中被调用的

/**
 * A dep is an observable that can have multiple
 * directives subscribing to it.
 */
var Dep = function Dep () {
 this.id = uid++;
 this.subs = [];
};
//设置某个Watcher的依赖
//这里添加Dep.target,用来判断是不是Watcher的构造函数调用
//也就是其this.get调用
Dep.prototype.depend = function depend () {
 if (Dep.target) {
  Dep.target.addDep(this);
 }
};
//在该方法中会触发subs的update方法
Dep.prototype.notify = function notify () {
 // stabilize the subscriber list first
 var subs = this.subs.slice();
 if (!config.async) {
  // subs aren't sorted in scheduler if not running async
  // we need to sort them now to make sure they fire in correct
  // order
  subs.sort(function (a, b) { return a.id - b.id; });
 }
 for (var i = 0, l = subs.length; i < l; i++) {
  subs[i].update();
 }
};

3、watch

初始化watch,函数中会调用createWatcher,createWatcher会调用$watch,$watch调用new Watcher实例。

function initWatch (vm, watch) {
 for (var key in watch) {
  var handler = watch[key];
  if (Array.isArray(handler)) {
   for (var i = 0; i < handler.length; i++) {
    createWatcher(vm, key, handler[i]);
   }
  } else {
   createWatcher(vm, key, handler);
  }
 }
}
function createWatcher (
 vm,
 expOrFn,
 handler,
 options
) {
 if (isPlainObject(handler)) {
  options = handler;
  handler = handler.handler;
 }
 if (typeof handler === 'string') {
  handler = vm[handler];
 }
 return vm.$watch(expOrFn, handler, options)
}
Vue.prototype.$watch = function (
 expOrFn,
 cb,
 options
) {
 var vm = this;
 if (isPlainObject(cb)) {
  return createWatcher(vm, expOrFn, cb, options)
 }
 options = options || {};
 options.user = true;
 var watcher = new Watcher(vm, expOrFn, cb, options);
 if (options.immediate) {
  try {
   cb.call(vm, watcher.value);
  } catch (error) {
   handleError(error, vm, ("callback for immediate watcher \"" + (watcher.expression) + "\""));
  }
 }
 return function unwatchFn () {
  watcher.teardown();
 }
};
}

2、computed

初始化computed,调用new Watcher(),并通过defineComputed函数将计算属性挂载到vue实例上,使计算属性可以在模板中使用

var computedWatcherOptions = { lazy: true }
function initComputed (vm, computed) {
 // $flow-disable-line
 var watchers = vm._computedWatchers = Object.create(null);
 // computed properties are just getters during SSR
 var isSSR = isServerRendering();
 for (var key in computed) {
  var userDef = computed[key];
  var getter = typeof userDef === 'function' ? userDef : userDef.get;
  //getter也就是computed的函数
  if (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
   );
  }
  //组件定义的计算属性已在
  //组件原型。我们只需要定义定义的计算属性
  //在这里实例化。
  if (!(key in vm)) {
   defineComputed(vm, key, userDef);
  } else {
   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);
   }
  }
 }
}
function defineComputed (
 target,
 key,
 userDef
) {
 var shouldCache = !isServerRendering();//true
 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 (sharedPropertyDefinition.set === noop) {
  sharedPropertyDefinition.set = function () {
   warn(
    ("Computed property \"" + key + "\" was assigned to but it has no setter."),
    this
   );
  };
 }
 Object.defineProperty(target, key, sharedPropertyDefinition);
}
//computed的getter函数,在模板获取对应computed数据时会调用
function createComputedGetter (key) {
 return function computedGetter () {
  var watcher = this._computedWatchers && this._computedWatchers[key];
  if (watcher) {
   if (watcher.dirty) {//true
    watcher.evaluate();//该方法会调用watcher.get方法,也就是computed对应的函数
   }
   if (Dep.target) {
    watcher.depend();
   }
   return watcher.value
  }
 }
}

通过以上代码可以看到watch和computed都是通过new Watcher实例实现数据的监听的,但是computed的options中lazy为true,这个参数导致它们走的是两条不同路线。

computed:模板获取数据时,触发其getter函数,最终调用watcher.get,也就是调用对应回调函数。

watch:模板获取数据时,触发其getter函数,将watcher添加到对应的Dep.subs中,在之后setter被调用时,Dep.notify通知所有watcher进行update,最终调用watcher.cb,也就是调用对应回调函数。

3、Watcher

构造函数在是watch时,会最后调用this.get,会触发属性的getter函数,将该Watcher添加到Dep的subs中,用于通知数据变动时调用。

调用Watcher实例的update方法会触发其run方法,run方法中会调用触发函数。其depend方法会调用new Dep的depend方法,dep的depend会调用Watcher的addDep方法,最终会把该watcher实例添加到Dep的subs属性中

/**
  *观察者解析表达式,收集依赖项,
  *并在表达式值更改时激发回调。
  *这用于$watch()api和指令。
  */
 var Watcher = function Watcher (
  vm,
  expOrFn,
  cb,
  options,
  isRenderWatcher
 ) {
  this.vm = vm;
 ......
  this.cb = cb;//触发函数
  this.id = ++uid$2; // uid for batching
  this.active = true;
  this.dirty = this.lazy; // for lazy watchers
 ......
  this.value = this.lazy ? undefined ? this.get();//computed会返回undefined,而watch会执行Watcher.get
 };
 /**
  * Scheduler job interface.
  * Will be called by the scheduler.
  * 该方法会执行触发函数
  */
 Watcher.prototype.run = function run () {
  if (this.active) {
   var value = this.get();
   if (
    value !== this.value ||
    // Deep watchers and watchers on Object/Arrays should fire even
    // when the value is the same, because the value may
    // have mutated.
    isObject(value) ||
    this.deep
   ) {
    // set new value
    var oldValue = this.value;
    this.value = value;
    if (this.user) {
     try {
      this.cb.call(this.vm, value, oldValue);
     } catch (e) {
      handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\""));
     }
    } else {
     this.cb.call(this.vm, value, oldValue);
    }
   }
  }
 };
 /**
  * Evaluate the getter, and re-collect dependencies.
  */
 Watcher.prototype.get = function get () {
  pushTarget(this);
  var value;
  var vm = this.vm;
  try {
   value = this.getter.call(vm, vm);
  } catch (e) {
   if (this.user) {
    handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));
   } else {
    throw e
   }
  } finally {
   // "touch" every property so they are all tracked as
   // dependencies for deep watching
   if (this.deep) {
    traverse(value);
   }
   popTarget();
   this.cleanupDeps();
  }
  return value
 };
 /**
  * Subscriber interface.
  * Will be called when a dependency changes.
  * 在方法中调用Watcher的run方法
  */
 Watcher.prototype.update = function update () {
  /* istanbul ignore else */
  if (this.lazy) {
   this.dirty = true;
  } else if (this.sync) {
   this.run();
  } else {
   queueWatcher(this);//该方法最终也会调用run方法
  }
 };
 /**
  * Depend on all deps collected by this watcher.会调用new Dep的depend方法,dep的depend会调用Watcher的addDep方法
  */
 Watcher.prototype.depend = function depend () {
  var i = this.deps.length;
  while (i--) {
   this.deps[i].depend();
  }
 };
 /**
  * Add a dependency to this directive.
  */
 Watcher.prototype.addDep = function addDep (dep) {
  var id = dep.id;
  if (!this.newDepIds.has(id)) {
   this.newDepIds.add(id);
   this.newDeps.push(dep);
   if (!this.depIds.has(id)) {
    dep.addSub(this);
   }
  }
 };

总结

以上所述是小编给大家介绍的vue中watch和computed为什么能监听到数据的改变以及不同之处,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

(0)

相关推荐

  • vue中计算属性(computed)、methods和watched之间的区别

    前言 本文主要给大家介绍了关于vue中计算属性(computed).methods和watched之间的区别,分享出来供大家参考学习,下面来一起看看详细的介绍: 计算属性 和普通属性一样是在模板中绑定计算属性的,当data中对应数据发生改变时,计算属性的值也会发生改变. Methods methods是方法,只要调用它,函数就会执行. 相同:两者达到的效果是同样的. 不同:计算属性是基于它们的依赖进行缓存的,只有相关依赖会发生改变时才会重新求职.只要相关依赖未改变,只会返回之前的结果,不再执行函

  • Vue.js每天必学之计算属性computed与$watch

    在模板中绑定表达式是非常便利的,但是它们实际上只用于简单的操作.模板是为了描述视图的结构.在模板中放入太多的逻辑会让模板过重且难以维护.这就是为什么 Vue.js 将绑定表达式限制为一个表达式.如果需要多于一个表达式的逻辑,应当使用**计算属性**. 基础例子 <div id="example"> a={{ a }}, b={{ b }} </div> var vm = new Vue({ el: '#example', data: { a: 1 }, comp

  • Vue.js计算属性computed与watch(5)

    在模板中绑定表达式是非常便利的,但是它们实际上只用于简单的操作.模板是为了描述视图的结构.在模板中放入太多的逻辑会让模板过重且难以维护.这就是为什么 Vue.js 将绑定表达式限制为一个表达式.如果需要多于一个表达式的逻辑,应当使用**计算属性**. Vue实例的computed的属性 <div class="test"> <p>原始的信息{{message}}</p> <p>计算后的信息{{ComputedMessage}}</p

  • Vue的watch和computed方法的使用及区别介绍

    Vue的watch属性 Vue的watch属性可以用来监听data属性中数据的变化 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="lib/vue.min.js"></script> <script src="lib/vue-router-3

  • Vue中的methods、watch、computed的区别

    看到这个标题就知道这篇文章接下来要讲的内容,我们在使用vue的时候methods.watch.computed这三个特性一定经常使用,因为它们是非常的有用,但是没有彻底的理解它们的区别和各自的使用场景,也很难用好它们,希望接下来的介绍为你答疑解惑. computed 我们先来看计算属性:computed,光看名字也知道是用来干什么的,计算属性当然是用来计算的,但是是怎么计算的呢?计算属性有两个显著的特点: 计算属性计算时所依赖的属性一定是响应式依赖,否则计算属性不会执行 计算属性是基于依赖进行缓

  • 详解vue中computed 和 watch的异同

    一.computed 和 watch 都可以观察页面的数据变化.当处理页面的数据变化时,我们有时候很容易滥用watch. 而通常更好的办法是使用computed属性,而不是命令是的watch回调. 这里我直接引用vue官网的例子来说明: html: 我们要实现 第三个表单的值 是第一个和第二个的拼接,并且在前俩表单数值变化时,第三个表单数值也在变化 <div id="myDiv"> <input type="text" v-model="

  • vue中watch和computed为什么能监听到数据的改变以及不同之处

    先来个流程图,水平有限,凑活看吧-_-|| 首先在创建一个Vue应用时: var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }) Vue构造函数源码: //创建Vue构造函数 function Vue (options) { if (!(this instanceof Vue) ) { warn('Vue is a constructor and should be called with the `new` keyw

  • Vue中watch、computed、updated三者的区别及用法

    1.watch 理解: 监听器,监听某个数据的变化从而来执行一些操作,当data里面的数据发生变化的时候来执行一下开销较大或异步的操作 1.监听值类型(简单类型)数据 //在一个vue实例中 new Vue({ el:"#myApp", data:{ num1:1, num2:2 }, methods:{}, watch:{ //这里两个属性,第一个值是变化后最新的值,第二个是变化前 num1(after,before){ this.num2 = after +1 } immediat

  • vue中watch和computed的区别与使用方法

    computed 计算属性说明: computed 是基于响应性依赖来进行缓存的.只有依赖数据发生改变,才会重新进行计算(当触发重新渲染,若依赖数据没有改变,则 computed 不会重新计算).若没改变,计算属性会立即返回之前缓存的计算结果. 不支持异步,当 computed 内有异步操作时无效,无法监听数据的变化的值. computed 中的成员可以只定义一个函数作为只读属性, 也可以定义成 get/set 变成可读写属性 如果一个属性是由其他属性计算而来的,这个属性依赖其他属性,是一个多对

  • 浅析Vue中method与computed的区别

    在new Vue的配置参数中的computed和methods都可以处理大量的逻辑代码,但是什么时候用哪个属性,要好好区分一下才能做到正确的运用vue. computed称为计算属性,顾名思义,计算就要返回一个计算的结果,所以,当我们要处理大量的逻辑,但是最后要取得最后的结果的时候可以用computed: 为了说明method与computed的区别,在此我想先来看看computed属性在vue官网中的说法:模板内的表达式是非常便利的,但是它们实际上只用于简单的运算.在模板中放入太多的逻辑会让模

  • Vue 中 filter 与 computed 的区别与用法解析

    watch与computed.filter: watch:监控已有属性,一旦属性发生了改变就去自动调用对应的方法 computed:监控已有的属性,一旦属性的依赖发生了改变,就去自动调用对应的方法 filter:js中为我们提供的一个方法,用来帮助我们对数据进行筛选 watch与computed的区别: 1.watch监控现有的属性,computed通过现有的属性计算出一个新的属性 2.watch不会缓存数据,每次打开页面都会重新加载一次, 但是computed如果之前进行过计算他会将计算的结果

  • 关于vue中计算属性computed的详细讲解

    目录 1.定义 2.用法 3.computed的响应式依赖(缓存) 4.应用场景 附:计算属性的 getter 与 setter 总结 1.定义 computed是vue的计算属性,是根据依赖关系进行缓存的计算,只有在它的相关依赖发生改变时才会进行更新 2.用法 一般情况下,computed默认使用的是getter属性 3.computed的响应式依赖(缓存) 1. computed的每一个计算属性都会被缓存起来,只要计算属性所依赖的属性发生变化,计算属性就会重新执行,视图也会更新.下面代码中,

  • vue使用$emit时,父组件无法监听到子组件的事件实例

    vue使用$emit时,父组件无法监听到子组件的事件的原因是$emit传入的事件名称只能使用小写,不能使用大写的驼峰规则命名 <div id="counter-event-example"> <p>{{ total }}</p> <button-counter v-on:ee="incrementTotal"></button-counter> <button-counter v-on:eEvent=

  • vue中通过使用$attrs实现组件之间的数据传递功能

    组件之间传递数据的方式有很多种,之所以有这么多种方式,是为了满足在不同场景不同条件下的使用. 一般有三种方式: props vuex Vue Event Bus 本文介绍的是使用$attrs的方式. 这是$attrs的官网api https://cn.vuejs.org/v2/api/#vm-attrs 这个api是在2.4版本中添加的,那么为什么要添加这个特性呢? 看看官网是怎么解释的 包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 ( class  和  style  除外

  • vue中前进刷新、后退缓存用户浏览数据和浏览位置的实例讲解

    vue中,我们所要实现的一个场景就是: 1.搜索页面==>到搜索结果页时,搜索结果页面要重新获取数据, 2.搜索结果页面==>点击进入详情页==>从详情页返回列表页时,要保存上次已经加载的数据和自动还原上次的浏览位置. 最近在项目中遇到这个问题,思考了几套方案,总是不太完善.百度搜到的方案也基本都只能满足一些很简单的需求.对于复杂一些的情况,还是有些不完善的地方.以下是个人对于这种场景的一个摸索,也参考了百度.如有更好的方案,欢迎指出. 缓存组件,vue2中提供了keep-alive.首

  • vue中计算属性computed理解说明包括vue侦听器,缓存与computed的区别

    一.计算属性(computed) 1.vue computed 说明 当一些数据需要根据其它数据变化时,需要进行处理才能去展示,虽然vue提供了绑定数据表达式绑定的方式,但是设计它的初衷只是用于简单运算的.在模板中放入太多的逻辑会让模板过重且难以维护,对于一些比较复杂和特殊的计算有可能就捉襟见肘了,而且计算的属性写在模板里也不利于项目维护 computed主要的作用: 分离逻辑(模板和数据分离) 缓存值 双向绑定(getter,setter) 2.语法格式 格式 computed:{ [key:

随机推荐