计算属性computed和watch侦听器

计算属性——缓存机制:仅当依赖的属性发生变化时,计算属性才会重新进行计算。get和set方法。计算属性是基于它们的响应式依赖进行缓存的,Date.now()不是响应式的依赖,computed 最大特点就是缓存,

方法实现计算属性:没有缓存机制,页面重新渲染就会调用方法。

watch侦听器——缓存机制:监听复杂数据类型(同源问题)——https://blog.csdn.net/weixin_43837268/article/details/96347840

computed计算属性和watch监听器的区别:https://segmentfault.com/a/1190000012948175?utm_source=tag-newest

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=
  , initial-scale=1.0">
  <title>Document</title>
  <script src="./node_modules/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <h1>age {{age}}</h1>
    <h1>计算属性{{fullName}}</h1>
    <h1>方法{{getFullName()}}</h1>
    <h1>watch{{watchFullName}}</h1>
    <h1>computed复杂数据{{arrName}}</h1>
    <h1>watch复杂数据{{watchArrName}}</h1>
  </div>
  <script>
    let vm=new Vue({
      el:'#app',
      data:{
        firstName:'Dell',
        lastName:'Lee',
        age:23,
        watchFullName:'Dell Lee',
        watchArrName:'ssj',
        arr:[
          {name:'ssj'}
        ]
      },
      //计算属性  有缓存机制,仅当依赖的属性发生变化时才进行计算
      computed:{
        //data中不能定义fullName变量
        fullName:function(){
          console.log('计算属性调用');
          return this.firstName+' '+this.lastName;
        },
        arrName:function(){
          return '数组中第一个对象的名字是:'+this.arr[0].name;
        },
        //解决watch数据同源问题
        arrJSON:function(){
          return JSON.parse(JSON.stringify(this.arr));
        }
      },
      //方法   无缓存机制,页面一旦重新渲染就会调用
      methods:{
        getFullName:function(){
          console.log('方法调用');
          return this.firstName+' '+this.lastName;
        }
      },
      //侦听器 有缓存机制,但是需要知道初始值
      watch:{
        firstName:function(){
          this.watchFullName=this.firstName+' '+this.lastName;
        },
        lastName:function(){
          this.watchFullName=this.firstName+' '+this.lastName;
        },
        arr:{
          deep:true,
          handler:function(newValue,oldValue){
            //这里old和new输出一致,是数据同源问题导致的,需要结合计算属性进行操作(通过JSON转换)
            console.log(oldValue[0].name);
            console.log(newValue[0].name);
            this.watchArrName=newValue[0]['name'];
          }
        },
        arrJSON:{ //配合computed使用
          deep:true,
          handler:function(newValue,oldValue){
            console.log(oldValue[0].name);
            console.log(newValue[0].name);
            this.watchArrName=newValue[0]['name'];
          }
        }
      }
    })
  </script>
</body>
</html>

 

posted @ 2020-02-17 15:09  聂小恶  阅读(292)  评论(0编辑  收藏  举报