网络日志

【Vue】computed

完整可运行代码

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <p> {{ number }} </p>
    <p> double1: {{ double1 }} </p>
    <input v-model="double2">
    {{ double2 }}
  </div>
</body>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      number: 5
    },
    computed: {
      double1() {
        // 当 double1 变化时才会重新执行
        return this.number * 2
      },
      // double2() {
      //   // 修改 input 报错,需要 setter
      //   return this.number * 2
      // },
      double2: {
        get: function() {
          return this.number * 2
        },
        // 修改需要 setter 拦截
        set: function(v) {
          this.number = v / 2
        }
      },
    }
  })
</script>
</html>