实例 Vue 使用 $watch() 方法中的函数来监听多个值的更改

x
 
<template>
  <h2>Example $watch() Method</h2>
  <p>Using a function as the first argument in the watcher to watch for changes in the sum of value A and value B.</p>
  <div>
    <p>Register a new country for Stuart to live in:</p>
    <p>Value A: <input type="range" min="-10" max="20" v-model="inpValA"> {{ inpValA }}</p>
    <p>Value B: <input type="range" min="-10" max="20" v-model="inpValB"> {{ inpValB }}</p>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
</template>
<script>
export default {
  data() {
    return {
      inpValA: 2,
      inpValB: 4,
      watchMessages: []
    };
  },
  mounted() {
    this.$watch( 
      ()=> Number(this.inpValA) + Number(this.inpValB), 
      function (newVal,oldVal) {
        this.watchMessages.push('watcher triggered. A + B = ' + newVal)
      }
    );
  }
};
</script>
<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
li {
  background-color: lightgreen;
}
</style>                  

输出结果