Vue中computed和watch使用场景和方法

原始学习网站:https://blog.csdn.net/qq_32614411/article/details/81745967

 自己学习心得:

    watch和computed都是以Vue的依赖追踪机制为基础,自动调用相关的函数去实现数据的变动。

    一,methods函数:

    一般的双向绑定,都需要在data里面写属性名,实现双向变化,需要手动调用  例如: this.函数() 

    二,computed函数:(计算  多对一)多个数据对一个数据影响   ,它会自动改变,不是函数,不可调用。(computer 只有与之相关的数据改变时改变)有自己的get  和 set 属性

    例如:

 computed:{

    name: {
      get () {
        console.log('new name')
        return `${this.firstName} ${this.lastName}`
      },
      set (name) {
        const names = name.split(' ')
        this.firstName = names[0]
        this.lastName = names[1]
      }

     }

    绑定不需要再data里面存数字,它自带缓存的功能,整个页面基本只计算一次,

   三,watch函数:(看 一对多)一个数据影响多个数据

    只有数据给改变的时候才会执行,第一次不会执行,

  name: {      get () {        console.log('new name')        return `${this.firstName} ${this.lastName}`      },      set (name) {        const names = name.split(' ')        this.firstName = names[0]        this.lastName = names[1]      }    }
--------------------- 版权声明:本文为CSDN博主「Hayley2016」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。原文链接:https://blog.csdn.net/qq_32614411/article/details/81745967

猜你喜欢

转载自www.cnblogs.com/maibao666/p/11347446.html