Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Vue $watch() 方法


示例

使用 $watch() 方法创建侦听器,每次 'value' 数据属性更改时写入新消息。

mounted() {
  this.$watch('value', function() {
    this.results.push('$watch() method')
  })
}
运行示例 »

查看下面更多示例。


定义和用法

The $watch() 方法用于创建侦听器。

The $watch() 方法返回一个停止函数,我们可以使用它来停止侦听器。 (参见示例 4)

侦听器用于监视值的变化(第一个参数),并在发生变化时执行某些操作(第二个参数)。也可以为侦听器定义其他属性(第三个参数)。

参数 描述
侦听源 必需。第一个参数是侦听源。这可以是组件属性名称字符串 (上面的示例),一个简单的点分隔路径字符串 (示例 5),或一个函数 (示例 6)。
回调函数 必需。第二个参数是一个回调函数,当侦听源发生变化时运行。回调函数可以设置为接收侦听源的新旧值作为参数 (参见示例 1)。
选项对象 可选。在这里我们可以指定选项 deep、immediate、flush 和 onTrigger/onTrack。

deep: 默认值为 'false'。如果侦听器是深度的,它也会对侦听器设置的属性的更深层面的变化做出反应。 (参见示例 2)

immediate: 默认值为 'false'。在侦听器创建后立即触发侦听器。第一次触发侦听器时旧值为 'undefined',此时 'immediate' 设置为 'true'。 (参见示例 3)

flush: 默认值为 'pre'。指定相对于组件渲染时运行回调函数的时间。可能的值是 'pre'、'post' 和 'sync'。谨慎使用此 flush 选项。

onTrigger/onTrack: 用于调试。仅在开发模式下有效。

注意: 也可以使用 watch 选项创建侦听器。


更多示例

示例 1

使用 $watch() 方法,每次 'value' 数据属性更改时,都用新旧值写入一条新消息。

<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>
运行示例 »

示例 2

使用 $watch() 方法,并将 deep 侦听选项设置为 'true'。侦听器现在可以检测 'value' 对象内部的变化。

<template>
  <h2>Example $watch() Method</h2>
  <p>Register an extra hobby for Stuart. The hobbies are stored in an array inside the 'value' object. The $watch() method
    is triggered because the 'deep' option is set to 'true' so that the watcher also detects changes further inside the
    object.</p>
  <div>
    <p>Register an extra hobby for Stuart:</p>
    <p><input type="text" ref="inpText"></p>
    <button v-on:click="regHobby">Register</button>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
  <p>Current 'value' object:</p>
  <pre>{{ this.value }}</pre>
</template>

<script>
export default {
  data() {
    return {
      value: {
        owner: 'Stuart',
        address: 'Faraway Lane',
        hobbies: ['Bird watching', 'Trail running']
      },
      watchMessages: []
    };
  },
  methods: {
    regHobby() {
      this.value.hobbies.push(this.$refs.inpText.value);
      this.$refs.inpText.value = null;
      this.$refs.inpText.focus();
    }
  },
  mounted() {
    this.$watch('value', function () {
      this.watchMessages.push('watcher triggered')
    }, {
      deep: true
    });
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}

li {
  background-color: lightgreen;
}</style>
运行示例 »

示例 3

使用 $watch() 方法,并将 immediate 侦听选项设置为 'true'。侦听器现在也会在创建后立即触发。

<template>
  <h2>Example $watch() Method</h2>
  <p>With the 'immediate' option set to 'true' the watcher is also triggered right after it is created.</p>
  <div>
    <input type="range" min="0" max="10" v-model="value"> Current value: {{ value }}
    <p>Messages from the watcher:</p>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: 4,
      watchMessages: []
    };
  },
  mounted() {
    this.$watch('value', (newVal, oldVal) => {
      this.watchMessages.push('Old value: '+oldVal+' New value: '+newVal)
    }, {
      immediate: true
    });
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}

li:first-child {
  background-color: lightgreen;
}</style>
运行示例 »

示例 4

使用 $watch() 方法返回的停止函数来停止侦听器。

<template>
  <h2>Example $watch() Method</h2>
  <p>Drag the slider to see the watcher work, click the stop button, and drag the slider again to confirm that the watcher has now stopped.</p>
  <div>
    <p><input type="range" min="0" max="10" v-model="value"> Current value: {{ value }}</p>
    <button v-on:click="stopFunc">Stop Watcher</button>
    <ol>
      <li v-for="x in results">{{ x }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: 4,
      results: [],
      stopFunc: null
    };
  },
  mounted() {
    this.stopFunc = this.$watch('value', function() {
      this.results.push('$watch() method')
    })
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
</style>
运行示例 »

示例 5

使用点分隔路径字符串,以便 $watch() 方法可以监听 'value' 对象内部的 'country' 属性。

<template>
  <h2>Example $watch() Method</h2>
  <p>The watcher is set up to watch 'value.country' and will therefore detect when the country is changed inside the 'value' object.</p>
  <div>
    <p>Register a new country for Stuart to live in:</p>
    <p><input type="text" v-model="inpVal"></p>
    <button v-on:click="regHobby">Register</button>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
  <p>Current 'value' object:</p>
  <pre>{{ this.value }}</pre>
</template>

<script>
export default {
  data() {
    return {
      inpVal: null,
      value: {
        owner: 'Stuart',
        address: 'Faraway Lane',
        country: 'Mexico'
      },
      watchMessages: []
    };
  },
  methods: {
    regHobby() {
      this.value.country = this.inpVal;
      this.inpVal = null;
    }
  },
  mounted() {
    this.$watch('value.country', function () {
      this.watchMessages.push('watcher triggered')
    });
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
</style>
运行示例 »

示例 6

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

<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>
运行示例 »

相关页面

Vue 教程: Vue 侦听器

Vue 教程: Vue 方法

Vue 教程: Vue v-on 指令

Vue 教程: Vue 模板引用

Vue 参考: Vue $refs 对象

JavaScript 教程: JS 箭头函数


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.