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

What is the purpose of the watchEffect function in Vuejs ?

1个答案

1

In Vue.js, the watchEffect function is used to monitor changes in reactive data and execute side effects. When the reactive state being observed by watchEffect changes, watchEffect will re-execute.

Main Uses

  1. Automatic Dependency Detection: Unlike watch, watchEffect does not require explicitly specifying the data source to observe; it automatically collects dependencies. This means all reactive references used within the callback function of watchEffect will be monitored.

  2. Simplified Side Effect Implementation: watchEffect is ideal for scenarios where side effects need to be executed after data changes, such as automatic data saving and view updates.

Example

Suppose you have a Vue component containing a form and a user object. You want to automatically save this data when user data changes. Using watchEffect can succinctly implement this requirement:

vue
<template> <div> <input v-model="user.name" placeholder="Enter your name"> <input v-model="user.age" placeholder="Enter your age"> </div> </template> <script> import { watchEffect, reactive } from 'vue'; export default { setup() { const user = reactive({ name: '', age: 0 }); watchEffect(() => { console.log('Detected change in user data:', user); // Assume saveUser is a function to save user data to the server saveUser(user); }); return { user }; } } </script>

In this example, watchEffect automatically monitors changes to the name and age properties of the user object. Once these data are updated, the code inside watchEffect executes, invoking the saveUser function to handle data saving.

In summary, watchEffect is a valuable feature that enables developers to automatically handle reactive data changes in a declarative manner.

2024年7月29日 20:04 回复

你的答案