实例 Vue 每次 'value' 数据属性更改时,使用 $watch() 方法编写一条包含新旧值的新消息

x
 
<template>
  <h2>Example $watch() Method</h2>
  <p>Drag the slider to change the value so that the $watch() method is triggered. The callback function writes a message with the new and old values.</p>
  <div>
    <p><input type="range" min="0" max="10" v-model="value"> Current value: {{ value }}</p>
    <ol>
      <li v-for="x in results">{{ x }}</li>
    </ol>
  </div>
</template>
<script>
export default {
  data() {
    return {
      value: 4,
      results: []
    };
  },
  mounted() {
    this.$watch('value', function(newVal, oldVal) {
      this.results.push('Old value:'+oldVal+', new value: '+newVal)
    })
  }
};
</script>
<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
</style>                  

输出结果