← Back to Vue.js Course | Chapter 9: Composables & Composition API | Lesson 6 of 7

watch/watchEffect का उपयोग

watch specific sources पर react करता है, जबकि watchEffect तुरंत चलता है और जो भी यह अंदर पढ़े वह बदलने पर फिर से चलता है।

In this page:

  1. watch/watchEffect
Syntax
markup
watch(source, (newValue, oldValue) => {
  // react to change
});

watchEffect(() => {
  // runs immediately and re-runs when used values change
});

watch/watchEffect

watch(source, callback) default से lazy है और new और old values देता है। watchEffect(fn) तुरंत चलता है, अंदर पढ़ी हर reactive value track करता है और बदलाव पर फिर से चलता है, बिना किसी old value के।

दोनों एक stop function return करते हैं और flush timing और cleanup callbacks support करते हैं।

Note: जब आपको old values या explicit sources चाहिए watch इस्तेमाल करें, और simple side effects के लिए watchEffect।

उदाहरण: watch/watchEffect

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app"><button @click="n++">n = {{ n }}</button><p>{{ log.join(" ; ") }}</p></div>
<script>
  Vue.createApp({
    setup() {
      const n = Vue.ref(1);
      const log = Vue.ref([]);
      Vue.watch(n, (newV, oldV) => log.value.push(`watch ${oldV}->${newV}`));
      Vue.watchEffect(() => log.value.push("effect sees " + n.value));
      return { n, log };
    },
  }).mount("#app");
  document.querySelector("button").click();
  Vue.nextTick(() => setTimeout(() => console.log(document.querySelector("p").textContent), 20));
</script>
</body>
</html>

<!-- Output:
Rendered: n = 2effect sees 1 ; watch 1->2 ; effect sees 2
console: effect sees 1 ; watch 1->2 ; effect sees 2
-->
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह उम्मीद करना कि watch तुरंत चलेगा
  2. Watchers asynchronously बनाना और इन्हें leak करना
  3. watchEffect में conditionally reactive values पढ़ना
चैप्टर सारांश
  • watch explicit और lazy है
  • watchEffect automatically track करता है
  • दोनों stop functions return करते हैं
  • watch old और new values देता है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.