网站地图    收藏   

主页 > 前端 > vue教程 >

Vue 2.0 侦听器 watch属性代码详解

来源:自学PHP网    时间:2019-07-23 15:24 作者:小飞侠 阅读:

[导读] Vue 2.0 侦听器 watch属性代码详解...

用法

牋牋牋牋牋 handler牋牋牋   ;对应的函数牋牋牋牋牋牋牋     牋牋牋牋牋 ;可以带两个参数,分别是新的值和旧的值,上下文为当前Vue实例
牋牋牋牋牋 immediate牋   ;侦听开始之后是否立即调用     ;默认为false
牋牋牋牋牋 sync牋牋牋    ;波尔值,是否同步执行,默认false牋牋 ;如果设置了这个属性,当数据有变化时就会立即执行了,否则放到下一个tick中排队执行




  
  
  Document


  

{{message}}

犜绰敕治觞/strong>
function initState (vm) {   //第3303行
 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);
 } else {
  observe(vm._data = {}, true /* asRootData */);
 }
 if (opts.computed) { initComputed(vm, opts.computed); }
 if (opts.watch && opts.watch !== nativeWatch) {      //如果传入了watch 且 watch不等于nativeWatch(细节处理,在Firefox浏览器下Object的原型上含有一个watch函数)
  initWatch(vm, opts.watch);                 //调用initWatch()函数初始化watch
 }
}

function initWatch (vm, watch) {  //第3541行
 for (var key in watch) {            //遍历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);        //调用createWatcher
  }
 }
}

function createWatcher (             //创建用户watcher
 vm,
 expOrFn,
 handler,
 options
) {
 if (isPlainObject(handler)) {           //如果handler是个对象,则将该对象的hanler属性保存到handler里面 从这里看到值可以是个对象
  options = handler;
  handler = handler.handler;          
 }
 if (typeof handler === 'string') {        
  handler = vm[handler];
 }
 return vm.$watch(expOrFn, handler, options)     //最后创建一个用户watch
}
Vue.prototype.$watch = function (   //第3596行
  expOrFn,                   //监听的属性,例如例子里的message
  cb,                      //对应的函数
  options                    //选项
 ) {
  var vm = this;
  if (isPlainObject(cb)) {
   return createWatcher(vm, expOrFn, cb, options)
  }
  options = options || {};
  options.user = true;                   //设置options.user为true,表示这是一个用户watch
  var watcher = new Watcher(vm, expOrFn, cb, options);   //创建一个Watcher对象
  if (options.immediate) {                    //如果有immediate选项,则直接运行
   cb.call(vm, watcher.value);
  }
  return function unwatchFn () {
   watcher.teardown();
  }
 };
}
var Watcher = function Watcher ( //第3082行
 vm,
 expOrFn,               //侦听的属性:message
 cb,                  //对应的函数
 options,
 isRenderWatcher
) {
 this.vm = vm;
 if (isRenderWatcher) {
  vm._watcher = this;
 }
 vm._watchers.push(this);
 // options
 if (options) {
  this.deep = !!options.deep;
  this.user = !!options.user;               //用户watch这里的user属性为true
  this.lazy = !!options.lazy;
  this.sync = !!options.sync;
 } else {
  this.deep = this.user = this.lazy = this.sync = false;
 }
 this.cb = cb;
 this.id = ++uid$1; // uid for batching
 this.active = true;
 this.dirty = this.lazy; // for lazy watchers
 this.deps = [];
 this.newDeps = [];
 this.depIds = new _Set();
 this.newDepIds = new _Set();
 this.expression = expOrFn.toString();
 // parse expression for getter
 if (typeof expOrFn === 'function') {         
  this.getter = expOrFn; 
 } else {                         //侦听器执行到这里,
  this.getter = parsePath(expOrFn);            //get对应的是parsePath()返回的匿名函数
  if (!this.getter) {
   this.getter = function () {};
   "development" !== 'production' && warn(
    "Failed watching path: \"" + expOrFn + "\" " +
    'Watcher only accepts simple dot-delimited paths. ' +
    'For full control, use a function instead.',
    vm
   );
  }
 }
 this.value = this.lazy
  ? undefined
  : this.get();                      //最后会执行get()方法
}; 
function parsePath (path) {       //解析路劲
 if (bailRE.test(path)) { 
  return
 }
 var segments = path.split('.');
 return function (obj) {        //返回一个函数,参数是一个对象
  for (var i = 0; i < segments.length; i++) {
   if (!obj) { return }
   obj = obj[segments[i]];
  }
  return obj
 }
}
Watcher.prototype.get = function get () {   //第3135行
 pushTarget(this);                 //将当前用户watch保存到Dep.target总=中
 var value;
 var vm = this.vm;
 try {
  value = this.getter.call(vm, vm);        //执行用户wathcer的getter()方法,此方法会将当前用户watcher作为订阅者订阅起来
 } 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();                  //恢复之前的watcher
  this.cleanupDeps();
 }
 return value
};时就会执行app.message方法,如下:
Watcher.prototype.update = function update () {  //第3200行 更新Watcher
 /* istanbul ignore else */
 if (this.lazy) {
  this.dirty = true;
 } else if (this.sync) {              //如果$this.sync为true,则直接运行this.run获取结果
  this.run();                   
 } else {
  queueWatcher(this);               //否则调用queueWatcher()函数把所有要执行update()的watch push到队列中
 }
};

Watcher.prototype.run = function run () {   //第3215行 执行,会调用get()获取对应的值 
 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) {            //如果是个用户 watcher
    try {
     this.cb.call(this.vm, value, oldValue);    //执行这个回调函数 vm作为上下文 参数1为新值 参数2为旧值     也就是最后我们自己定义的function(newval,val){ console.log(newval,val) }函数
    } catch (e) { 
     handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\""));
    }
   } else {
    this.cb.call(this.vm, value, oldValue);
   }
  }
 }
};总结
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论