美文网首页Vue学习笔记
Vue computed、methods、watch的简单区别

Vue computed、methods、watch的简单区别

作者: puxiaotaoc | 来源:发表于2018-12-30 22:07 被阅读2次
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <script src='./vue.js'></script>
</head>

<body>
  <div id="app">
    {{fullName}}
    <!-- {{fullName()}}  第二种方法 -->
    {{age}}
  </div>
  <script>
    // 生命周期函数就是vue实例在某一个时间点会自动执行的函数
    var vm = new Vue({
      el: '#app',
      data: {
        firstName: 'putao',
        lastName: 'c',
        fullName: 'puxiaotaoc',
        age: 228
      },
      // 计算fullName属性的几种方法
      // 第一种方法:计算属性具有缓存,只有当依赖的变量发生改变时才会进行重新计算,因此更新age,不会打印‘计算了一次’
      // computed: {
      //   fullName: function() {
      //     console.log('计算了一次');
      //     return this.firstName + this.lastName
      //   }
      // }

      // 第二种方法:methods中的方法不会被缓存,如果更新age,会打印出‘计算了一次’
      // methods: {
      //   fullName: function() {
      //     console.log('计算了一次');
      //     return this.firstName + this.lastName
      //   }
      // }

      // 第三种方法:监听器,和fullName不相关的变量发生变化,不会执行
      // watch和computed都可以实现缓存的功能,但watch的实现代码会多一些,所以更推荐使用computed
      watch: {
        firstName: function() {
          console.log('计算了一次');
          this.fullName = this.firstName + this.lastName;

        },
        lastName: function() {
          console.log('计算了一次');
          this.fullName = this.firstName + this.lastName;
        }
      }
    })
  </script>
</body>
</html>
// computed中的getter和setter
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <script src='./vue.js'></script>
</head>

<body>
  <div id="app">
    {{fullName}}
  </div>
  <script>
    // 生命周期函数就是vue实例在某一个时间点会自动执行的函数
    var vm = new Vue({
      el: '#app',
      data: {
        firstName: 'putao',
        lastName: 'c'
      },
      computed: {
        fullName: {
          get: function() {
            return this.firstName + this.lastName;
          },
          set: function(value) {
            var arr = value.split(' ');
            this.firstName = arr[0];
            this.lastName = arr[1];
          }

        }
      }
    })
  </script>
</body>

</html>

相关文章

网友评论

    本文标题:Vue computed、methods、watch的简单区别

    本文链接:https://www.haomeiwen.com/subject/kwsblqtx.html