Home > Web Front-end > Vue.js > body text

How to use watch in vue

下次还敢
Release: 2024-04-30 03:54:14
Original
1138 people have browsed it

Watch in Vue.js can be used to listen for changes in data properties and perform operations. The syntax is: watch(expression, callback, options). It supports using strings or functions to monitor data attributes, and calls callback functions when they change. You can configure whether to call immediately, whether to monitor deeply, and whether to update synchronously through options.

How to use watch in vue

Usage of watch in Vue.js

Watch in Vue.js is a reactive API that can Lets you listen for changes in data properties and perform actions based on those changes.

Syntax

<code class="js">watch(expression, callback, options)</code>
Copy after login

Parameters

  • expression: The data attribute to be monitored. It can be a string (property name) or a function (returning the value to be monitored).
  • callback: Function called when the data attribute changes. It receives two parameters: new value and old value.
  • options (optional): Optional object used to configure watch.

Example

<code class="js">// 使用字符串
watch('message', function (newValue, oldValue) {
  console.log(`Message changed from "${oldValue}" to "${newValue}".`);
});

// 使用函数
watch(function () {
  return this.count;
}, function (newValue, oldValue) {
  console.log(`Count incremented from ${oldValue} to ${newValue}.`);
});</code>
Copy after login

Options

  • immediate: Control whether watch The callback function is called immediately when the component is initialized. The default value is false.
  • deep: Control whether watch deeply monitors changes in objects and arrays. The default value is false.
  • sync: Control whether watch calls the callback function immediately after the data attribute changes. The default value is false.

Usage scenarios

Common scenarios for using watch include:

  • Updating the DOM when data attributes change
  • Trigger external actions (for example, make a request) when data attributes change
  • Respond to events from other components

The above is the detailed content of How to use watch in vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
vue
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template