乐闻世界logo
搜索文章和话题

How do you stop watching a property or expression using the watch function?

1个答案

1

In Vue.js, the watch function is used to observe and respond to changes in data on a Vue instance. If at some point you no longer need to observe changes to a particular data property, you can stop the watcher.

To stop the watch function, you first need to obtain a reference to it when creating the watcher. When you call vm.$watch() to create a watcher, it returns an unwatch function. You can call this returned function to stop the watcher.

Here is a specific example:

javascript
// Data object var data = { a: 1 }; // Create Vue instance, note that the data property is a function returning our defined data object var vm = new Vue({ data: function () { return data; } }); // Create watcher, observing the 'a' property var unwatch = vm.$watch('a', function (newValue, oldValue) { // This callback is called when 'a' changes console.log(`a's value changed from ${oldValue} to ${newValue}.`); }); // Change data, observe log output data.a = 2; // When no longer needed, call unwatch to stop observation unwatch(); // After this, modifying a's value will not trigger the watcher data.a = 3;

In the above code, we first define a data object and create a Vue instance. Then we create a watcher for the 'a' property using $watch and retain the returned unwatch function. When we no longer need this watcher, we stop the observation by calling unwatch(). After that, even if the data a changes, the watcher's callback function will no longer be triggered.

This approach applies to watchers created using Vue instance methods. If you declare a watcher using the watch option in a component, Vue will automatically stop all watchers when the component is destroyed, without manual intervention.

2024年7月19日 19:49 回复

你的答案