详解Vue中的Computed和Watch

开发 前端
作为一名Vue开发者,虽然在项目中频繁使用过computed和watch,但从来没有系统的学习过,总觉着对这两个知识点有些一知半解。

[[376061]]

本文转载自微信公众号「不知名宝藏程序媛  」,作者小土豆 。转载本文请联系不知名宝藏程序媛  公众号。  

 1. 前言

作为一名Vue开发者,虽然在项目中频繁使用过computed和watch,但从来没有系统的学习过,总觉着对这两个知识点有些一知半解。

如果你也和我一样,就一起来回顾和总结一下这两个知识点吧。

本篇非源码分析,只是从两者各自的用法、特性等做一些梳理。

2. Vue中的computed

Vue中的computed又叫做计算属性,Vue官网中给了下面这样一个示例。

模板中有一个message数据需要展示:

  1. <template> 
  2.   <div id="app"
  3.     {{message}} 
  4.   </div> 
  5. </template> 
  6. <script> 
  7. export default { 
  8.   name'App'
  9.   data() { 
  10.     return { 
  11.       message: 'Hello' 
  12.     } 
  13.   } 
  14. </script> 

假如此时有一个需求:对message进行反转并展示到模板中。

那最简单的实现方式就是直接在模板中做这样的转化:

  1. <template> 
  2.   <div id="app"
  3.     <p>{{message}}</p> 
  4.     <p>{{message.split('').reverse().join('')}}</p> 
  5.   </div> 
  6. </template> 

那这个时候,Vue官方告诉我们:过多的逻辑运算会让模板变得重且难以维护,而且这种转化无法复用,并指导我们使用计算属性-computed来实现这个需求。

  1. export default { 
  2.   name'App'
  3.   computed: { 
  4.     reverseMessage: function(){ 
  5.       return this.message.split('').reverse().join(''); 
  6.     } 
  7.   }, 
  8.   data() { 
  9.     return { 
  10.       message: 'Hello' 
  11.     } 
  12.   } 

在以上代码中我们定义了一个计算属性:reverseMessage,其值为一个函数并返回我们需要的结果。

之后在模板中就可以像使用message一样使用reverseMessage。

  1. <template> 
  2.   <div id="app"
  3.     <p>{{message}}</p> 
  4.     <p>{{reverseMessage}}</p> 
  5.   </div> 
  6. </template> 

那么此时有人肯定要说了,我用methods也能实现呀。确实使用methods也能实现此种需求,但是在这种情况下我们的计算属性相较于methods是有很大优势的,这个优势就是计算属性存在缓存。

如果我们使用methods实现前面的需求,当message的反转结果有多个地方在使用,对应的methods函数会被调用多次,函数内部的逻辑也需要执行多次;而计算属性因为存在缓存,只要message数据未发生变化,则多次访问计算属性对应的函数只会执行一次。

  1. <template> 
  2.   <div id="app"
  3.     <p>{{message}}</p> 
  4.     <p>第一次访问reverseMessage:{{reverseMessage}}</p> 
  5.     <p>第二次访问reverseMessage:{{reverseMessage}}</p> 
  6.     <p>第三次访问reverseMessage:{{reverseMessage}}</p> 
  7.     <p>第四次访问reverseMessage:{{reverseMessage}}</p> 
  8.   </div> 
  9. </template> 
  10.  
  11. <script> 
  12. export default { 
  13.   name'App'
  14.   computed: { 
  15.     reverseMessage: function(value){ 
  16.       console.log(" I'm reverseMessage" ) 
  17.       return this.message.split('').reverse().join(''); 
  18.     } 
  19.   }, 
  20.   data() { 
  21.     return { 
  22.       message: 'Hello' 
  23.     } 
  24.   } 
  25. </script> 

运行项目,查看结果,会发现计算属性reverseMessage对应的函数只执行了一次。

图片

 

3. Vue中的watchVue

中的watch又名为侦听属性,它主要用于侦听数据的变化,在数据发生变化的时候执行一些操作。

  1. <template> 
  2.   <div id="app"
  3.     <p>计数器:{{counter}}</p> 
  4.     <el-button type="primary" @click="counter++"
  5.       Click 
  6.     </el-button> 
  7.   </div> 
  8. </template> 
  9.  
  10. <script> 
  11. export default { 
  12.   name'App'
  13.   data() { 
  14.     return { 
  15.       counter: 0 
  16.     } 
  17.   }, 
  18.   watch: { 
  19.     /** 
  20.      * @name: counter 
  21.      * @description:  
  22.      *   监听Vue data中的counter数据 
  23.      *   当counter发生变化时会执行对应的侦听函数 
  24.      * @param {*} newValue counter的新值 
  25.      * @param {*} oldValue counter的旧值 
  26.      * @return {*} None 
  27.      */ 
  28.     counter: function(newValue, oldValue){ 
  29.       if(this.counter == 10){ 
  30.         this.counter = 0; 
  31.       } 
  32.     } 
  33.   } 
  34. </script> 

我们定义了一个侦听属性counter,该属性侦听的是Vue data中定义counter数据,整个的逻辑就是点击按钮counter加1,当counter等于10的时候,将counter置为0。

上面的代码运行后的结果如下:

 

图片

 

Vue官网很明确的建议我们这样使用watch侦听属性:当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的。

4. computed和watch之间的抉择

看完以上两部分内容,关于Vue中computed和watch的基本用法算是掌握了。但实际上不止这些,所以接下来我们在来进阶学习一波。

这里我们还原Vue官网中的一个示例,示例实现的功能大致如下:

 

图片

 

该功能可以简单的描述为:在firstName和lastName数据发生变化时,对fullName进行更新,其中fullName的值为firstName和lastName的拼接。

首先我们使用watch来实现该功能:watch侦听firstName和lastName,当这两个数据发生变化时更新fullName的值。

  1. <template> 
  2.   <div id="app"
  3.     <p>firstName: <el-input v-model="firstName" placeholder="请输入firstName"></el-input></p> 
  4.     <p>lastName: <el-input v-model="lastName" placeholder="请输入lastName"></el-input></p> 
  5.     <p>fullName: {{fullName}}</p> 
  6.   </div> 
  7. </template> 
  8.  
  9. <script> 
  10. export default { 
  11.   name'App'
  12.   data() { 
  13.     return { 
  14.       firstName: ''
  15.       lastName: ''
  16.       fullName: '(空)' 
  17.     } 
  18.   }, 
  19.   // 使用watch实现 
  20.   watch: { 
  21.     firstName: function(newValue) { 
  22.       this.fullName = newValue + ' ' + this.lastName; 
  23.     }, 
  24.     lastName: function(newValue){ 
  25.       this.fullName = this.firstName + ' ' + newValue; 
  26.     } 
  27.   } 
  28. </script> 

接着我们在使用computed来实现:定义计算属性fullName,将firstName和lastName的值进行拼接并返回。

  1. <template> 
  2.   <div id="app"
  3.     <p>firstName: <el-input v-model="firstName" placeholder="请输入firstName"></el-input></p> 
  4.     <p>lastName: <el-input v-model="lastName" placeholder="请输入lastName"></el-input></p> 
  5.     <p>fullName: {{fullName}}</p> 
  6.   </div> 
  7. </template> 
  8.  
  9. <script> 
  10. export default { 
  11.   name'App'
  12.   data() { 
  13.     return { 
  14.       firstName: ''
  15.       lastName: '' 
  16.     } 
  17.   } 
  18.   computed: { 
  19.     fullName: function() { 
  20.       return this.firstName + ' ' + this.lastName; 
  21.     } 
  22.   }  
  23. </script> 

我们发现computed和watch都可以实现这个功能,但是我们在对比一下这两种不同的实现方式:

  1. // 使用computed实现 
  2. computed: { 
  3.   fullName: function() { 
  4.     return this.firstName + ' ' + this.lastName; 
  5.   } 
  6. },  
  7. // 使用watch实现 
  8. watch: { 
  9.   firstName: function(newValue) { 
  10.     this.fullName = newValue + ' ' + this.lastName; 
  11.   }, 
  12.   lastName: function(newValue){ 
  13.     this.fullName = this.firstName + ' ' + newValue; 
  14.   } 

对比之下很明显的会发现发现computed的实现方式更简洁高级。

所以在日常项目开发中,对于computed和watch的使用要慎重选择:

 

图片

 

这两者选择和使用没有对错之分,只是希望能更好的使用,而不是滥用。

5. 计算属性进阶

接下来我们在对计算属性的内容进行进阶学习。

>>> 5.1 计算属性不能和Vue Data属性同名

在声明计算属性的时候,计算属性是不能和Vue Data中定义的属性同名,否则会出现错误:The computed property "xxxxx" is already defined in data。

如果有阅读过Vue源码的同学对这个原因应该会比较清楚,Vue在初始化的时候会按照:initProps-> initMethods -> initData -> initComputed -> initWatch这样的顺序对数据进行初始化,并且会通过Object.definedProperty将数据定义到vm实例上,在这个过程中同名的属性会被后面的同名属性覆盖。

通过打印组件实例对象,可以很清楚的看到props、methods、data、computed会被定义到vm实例上。

>>> 5.2 计算属性的set函数

在前面代码示例中,我们的computed是这么实现的:

  1. computed: { 
  2.   reverseMessage: function(){ 
  3.     return this.message.split('').reverse().join(''); 
  4.   } 
  5. }, 

这种写法实际上是给reverseMessage提供了一个get方法,所以上面的写法等同于:

  1. computed: { 
  2.   reverseMessage: { 
  3.     // 计算属性的get方法 
  4.     get: function(){ 
  5.       return this.message.split('').reverse().join(''); 
  6.     } 
  7.   } 
  8. }, 

除此之外,我们也可以给计算属性提供一个set方法:

  1. computed: { 
  2.   reverseMessage: { 
  3.     // 计算属性的get方法 
  4.     get: function(){ 
  5.       return this.message.split('').reverse().join(''); 
  6.     }, 
  7.     setfunction(newValue){ 
  8.        // set方法的逻辑 
  9.     } 
  10.   } 
  11. }, 

只有我们主动修改了计算属性的值,set方法才会被触发。

关于计算属性的set方法在实际的项目开发中暂时还没有遇到,不过经过一番思考,做出来下面这样一个示例:

 

图片

 

这个示例是分钟和小时之间的一个转化,利用计算属性的set方法就能很好实现:

  1. <template> 
  2.   <div id="app"
  3.     <p>分钟<el-input v-model="minute" placeholder="请输入内容"></el-input></p> 
  4.     <p>小时<el-input v-model="hours" placeholder="请输入内容"></el-input></p> 
  5.   </div> 
  6. </template> 
  7.  
  8. <script> 
  9. export default { 
  10.   name'App'
  11.   data() { 
  12.     return { 
  13.       minute: 60, 
  14.     } 
  15.   }, 
  16.   computed: { 
  17.     hours:{ 
  18.       get: function() { 
  19.         return this.minute / 60; 
  20.       }, 
  21.       setfunction(newValue) { 
  22.         this.minute = newValue * 60; 
  23.       } 
  24.     } 
  25.   }  
  26. </script> 

>>> 5.3 计算属性的缓存

前面我们总结过计算属性存在缓存,并演示相关的示例。那计算属性的缓存是如何实现的呢?

关于计算属性的缓存这个知识点需要我们去阅读Vue的源码实现,所以我们一起来看看源码吧。

相信大家看到源码这个词就会有点胆战心惊,不过不用过分担心,文章写到这里的时候考虑到本篇文章的内容和侧重点,所以不会详细去解读计算属性的源码,着重学习计算属性的缓存实现,并且点到为止。

那如果你没有仔细解读过Vue的响应式原理,那建议忽略这一节的内容,等对源码中的响应式有一定了解之后在来看这一节的内容会更容易理解。(我自己之前也写过的一篇相关文章:1W字长文+多图,带你了解vue2.x的双向数据绑定源码实现,点击文末阅读原文即可查看)

关于计算属性的入口源代码如下:

  1. /* 
  2. * Vue版本:v2.6.12 
  3. * 代码位置:/vue/src/core/instance/state.js 
  4. */ 
  5. export function initState (vm: Component) { 
  6.   // ......省略...... 
  7.   const opts = vm.$options 
  8.   // ......省略...... 
  9.   if (opts.computed) initComputed(vm, opts.computed) 
  10.   // ......省略                                                                       ...... 

接着我们来看看initComputed:

  1. /* 
  2. * Vue版本:v2.6.12 
  3. * 代码位置:/vue/src/core/instance/state.js 
  4. * @params: vm        vue实例对象 
  5. * @params: computed  所有的计算属性 
  6. */ 
  7. function initComputed (vm: Component, computed: Object) { 
  8.   
  9.   /*  
  10.   * Object.create(null):创建一个空对象 
  11.   * 定义的const watchers是用于保存所有计算属性的Watcher实例 
  12.   */ 
  13.   const watchers = vm._computedWatchers = Object.create(null
  14.   
  15.   // 遍历计算属性 
  16.   for (const key in computed) { 
  17.     const userDef = computed[key
  18.     /* 
  19.     * 获取计算属性的get方法  
  20.     * 计算属性可以是function,默认提供的是get方法 
  21.     * 也可以是对象,分别声明get、set方法 
  22.     */ 
  23.     const getter = typeof userDef === 'function' ? userDef : userDef.get 
  24.     
  25.     /*  
  26.     * 给计算属性创建watcher 
  27.     * @params: vm       vue实例对象  
  28.     * @params: getter   计算属性的get方法 
  29.     * @params: noop      
  30.           noop是定义在 /vue/src/shared/util.js中的一个函数 
  31.           export function noop (a?: any, b?: any, c?: any) {} 
  32.     * @params: computedWatcherOptions 
  33.     *     computedWatcherOptions是一个对象,定义在本文件的167行 
  34.     *     const computedWatcherOptions = { lazy: true } 
  35.     */ 
  36.     watchers[key] = new Watcher( 
  37.       vm, 
  38.       getter || noop, 
  39.       noop, 
  40.       computedWatcherOptions 
  41.     ) 
  42.     // 函数调用 
  43.     defineComputed(vm, key, userDef) 
  44.   } 

在initComputed这个函数中,主要是遍历计算属性,然后在遍历的过程中做了下面两件事:

  • 第一件:为计算属性创建watcher,即new Watcher
  • 第二件:调用defineComputed方法

那首先我们先来看看new Watcher都做了什么。

为了方便大家看清楚new Watcher的作用,我将Watcher的源码进行了简化,保留了一些比较重要的代码。

同时代码中重要的部分都添加了注释,有些注释描述的可能有点重复或者啰嗦,但主要是想以这种重复的方式让大家可以反复琢磨并理解源码中的内容,方便后续的理解 ~

  1. /* 
  2. * Vue版本:v2.6.12 
  3. * 代码位置: /vue/src/core/observer/watcher.js 
  4. * 为了看清楚Watcher的作用 
  5. * 将源码进行简化,所以下面是一个简化版的Watcher类 
  6. * 同时部分代码顺序有所调整 
  7. */ 
  8. export default class Watcher { 
  9.   constructor ( 
  10.     vm: Component, 
  11.     expOrFn: string | Function
  12.     cb: Function
  13.     options?: ?Object, 
  14.   ) { 
  15.     // vm为组件实例 
  16.     this.vm = vm   
  17.     // expOrFn在new Watcher时传递的参数为计算属性的get方法 
  18.     // 将计算属性的get方法赋值给watcher的getter属性 
  19.     this.getter = expOrFn 
  20.     // cb为noop:export function noop (a?: any, b?: any, c?: any) {} 
  21.     this.cb = cb   
  22.     // option在new Watcher传递的参数值为{lazy: true}  
  23.     // !!操作符即将options.lazy强转为boolean类型 
  24.     // 赋值之后this.lazy的值为true 
  25.     this.lazy = !!options.lazy  
  26.     // 赋值之后this.dirty的值true 
  27.     this.dirty = this.lazy  
  28.      
  29.     /* 
  30.     * 在new Watcher的时候因为this.lazy的值为true 
  31.     * 所以this.value的值还是undefined 
  32.     */ 
  33.     this.value = this.lazy ? undefined : this.get() 
  34.   } 
  35.   get () {  
  36.     const vm = this.vm 
  37.     /* 
  38.     * 在构造函数中,计算属性的get方法赋值给了watcher的getter属性 
  39.     * 所以该行代码即调用计算属性的get方法,获取计算属性的值 
  40.     */ 
  41.     value = this.getter.call(vm, vm) 
  42.     return value 
  43.   } 
  44.   evaluate () { 
  45.     /* 
  46.     * 调用watcher的get方法 
  47.     * watcher的get方法逻辑为:调用计算属性的get方法获取计算属性的值并返回 
  48.     * 所以evaluate函数也就是获取计算属性的值,并赋值给watcher.value 
  49.     * 并且将watcher.dirty置为false,这个dirty是实现缓存的关键 
  50.     */  
  51.     this.value = this.get() 
  52.     this.dirty = false 
  53.   } 

看了这个简化版的Watcher以后,想必我们已经很清楚的知道了Watcher类的实现。

那接下来就是关于缓存的重点了,也就是遍历计算属性做的第二件事:调用defineComputed函数:

  1. /* 
  2. * Vue版本:v2.6.12 
  3. * 代码位置:/vue/src/core/instance/state.js 
  4. * @params: target  vue实例对象 
  5. * @params: key     计算属性名 
  6. * @params: userDef 计算属性定义的function或者object 
  7. */ 
  8. export function defineComputed ( 
  9.   target: any
  10.   key: string, 
  11.   userDef: Object | Function 
  12. ) {   
  13.  
  14.   // ......暂时省略有关sharedPropertyDefinition的代码逻辑...... 
  15.    
  16.   /* 
  17.   * sharedPropertyDefinition本身是一个对象,定义在本文件31行: 
  18.   * const sharedPropertyDefinition = { 
  19.   *   enumerable: true
  20.   *   configurable: true
  21.   *   get: noop, 
  22.   *   set: noop 
  23.   * } 
  24.   * 最后使用Object.defineProperty传入对应的参数使得计算属性变得可观测 
  25.   */ 
  26.   Object.defineProperty(target, key, sharedPropertyDefinition) 

defineComputed方法最核心也只有一行代码,也就是使用Object.defineProperty将计算属性变得可观测。

那么接下来我们的关注点就是调用Object.defineProperty函数时传递的第三个参数:sharedPropertyDefinition。

sharedPropertyDefinition是定义在当前文件中的一个对象,默认值如下:

  1. const sharedPropertyDefinition = { 
  2.   enumerable: true
  3.   configurable: true
  4.   get: noop, 
  5.   set: noop 

前面贴出来的defineComputed源码中,我注释说明省略了一段有关sharedPropertyDefinition的代码逻辑,那省略的这段源代码就不展示了,它的主要作用就是在对sharedPropertyDefinition.get和sharedPropertyDefinition.set进行重写,重写之后sharedPropertyDefinition的值为:

  1. const sharedPropertyDefinition = { 
  2.   enumerable: true
  3.   configurable: true
  4.   get: function(){ 
  5.       // 获取计算属性对应的watcher实例 
  6.       const watcher = this._computedWatchers && this._computedWatchers[key
  7.       if (watcher) { 
  8.         if (watcher.dirty) { 
  9.           watcher.evaluate() 
  10.         } 
  11.         if (Dep.target) { 
  12.           watcher.depend() 
  13.         } 
  14.         return watcher.value 
  15.       } 
  16.     } 
  17.   }, 
  18.   // set对应的值这里写的是noop 
  19.   // 但是我们要知道set真正的值是我们为计算属性提供的set函数 
  20.   // 千万不要理解错了哦  
  21.   set: noop,   

那sharedPropertyDefinition.get函数的逻辑已经非常的清晰了,同时它的逻辑就是计算属性缓存实现的关键逻辑:在sharedPropertyDefinition.get函数中,先获取到计算属性对应的watcher实例;然后判断watcher.dirty的值,如果该值为false,则直接返回watcher.value;否则调用watcher.evaluate()重新获取计算属性的值。

关于计算属性缓存的源码分析就到这里,相信大家对计算属性的缓存实现已经有了一定的认识。不过仅仅是了解这些还不够,我们应该去通读计算属性的完整源码实现,才能对计算属性有一个更通透的认识。

6. 侦听属性进阶

>>> 6.1 handler

前面我们是这样实现侦听属性的:

  1. watch: { 
  2.   counter: function(newValue, oldValue){ 
  3.     if(this.counter == 10){ 
  4.       this.counter = 0; 
  5.     } 
  6.   } 

那上面的这种写法等同于给counter提供一个handler函数:

  1. watch: { 
  2.   counter: { 
  3.     handler: function(newValue, oldValue){ 
  4.       if(this.counter == 10){ 
  5.         this.counter = 0; 
  6.       } 
  7.     } 
  8.   } 

>>> 6.2 immediate

正常情况下,侦听属性提供的函数是不会立即执行的,只有在对应的vue data发生变化时,侦听属性对应的函数才会执行。

那如果我们需要侦听属性对应的函数立即执行一次,就可以给侦听属性提供一个immediate选项,并设置其值为true。

  1. watch: { 
  2.   counter: { 
  3.     handler: function(newValue, oldValue){ 
  4.       if(this.counter == 10){ 
  5.         this.counter = 0; 
  6.       } 
  7.     }, 
  8.     immediate: true 
  9.   } 

>>> 6.3 deep

如果我们对一个对象类型的vue data进行侦听,当这个对象内的属性发生变化时,默认是不会触发侦听函数的。

  1. <template> 
  2.   <div id="app"
  3.     <p><el-input v-model="person.name" placeholder="请输入姓名"></el-input></p> 
  4.     <p><el-input v-model="person.age" placeholder="请输入年龄"></el-input></p> 
  5.   </div> 
  6. </template> 
  7. <script> 
  8. export default { 
  9.   name'App'
  10.   data() { 
  11.     return { 
  12.       person: { 
  13.         name'jack'
  14.         age: 20 
  15.       } 
  16.     } 
  17.   }, 
  18.   watch: { 
  19.     person: function(newValue){ 
  20.       console.log(newValue.name + ' ' + newValue.age); 
  21.     } 
  22.   } 
  23. </script> 

监听对象类型的数据,侦听函数没有触发:

 

图片

 

通过给侦听属性提供deep: true就可以侦听到对象内部属性的变化:

  1. watch: { 
  2.   person: { 
  3.     handler: function(newValue){ 
  4.       console.log(newValue.name + ' ' + newValue.age); 
  5.     }, 
  6.     deep: true 
  7.   } 
图片

 

不过仔细观察上面的示例会发现这种方式去监听Object类型的数据,Object数据内部任一属性发生变化都会触发侦听函数,那如果我们想单独侦听对象中的某个属性,可以使用下面这样的方式:

  1. watch: { 
  2.   'person.name'function(newValue, oldValue){ 
  3.       // 逻辑 
  4.    } 

7.总结

到此本篇文章就结束了,内容非常的简单易懂,在此将以上的内容做以总结:

 

图片

 

学无止境,除了基础的内容之外,很多特性的实现原理也是我们应该关注的东西,但是介于本篇文章输出的初衷,所以对原理实现并没有完整的分析,后面有机会在总结~

原文链接:https://mp.weixin.qq.com/s/frWBXTa-EnhkGFn6c1X5NQ

 

责任编辑:武晓燕 来源: 不知名宝藏程序媛
相关推荐

2022-07-14 08:22:48

Computedvue3

2024-03-08 10:38:07

Vue响应式数据

2021-12-08 09:09:33

Vue 3 Computed Vue2

2023-11-28 17:49:51

watch​computed​性能

2023-03-29 14:25:08

Vue.js前端框架

2022-06-09 08:28:27

Vue3watchwatchEffec

2022-06-26 00:00:02

Vue3响应式系统

2021-12-07 05:44:45

Vue 3 Watch WatchEffect

2022-04-11 08:03:30

Vue.jscomputed计算属性

2023-12-11 07:34:37

Computed计算属性Vue3

2022-04-12 08:08:57

watch函数options封装

2024-03-22 08:57:04

Vue3Emoji表情符号

2024-03-21 08:34:49

Vue3WebSocketHTTP

2009-06-25 15:20:28

CollectionMap

2021-06-26 06:29:14

Vue 2Vue 3开发

2024-04-08 07:28:27

PiniaVue3状态管理库

2022-01-17 10:05:33

LinuxWatch命令

2021-09-22 15:00:24

Linuxwatch 命令

2020-11-02 11:33:52

ReactVue应用

2020-10-19 19:05:20

VueAxiosAPI
点赞
收藏

51CTO技术栈公众号