← Back to Vue.js Course | Chapter 3: Reactivity | Lesson 3 of 7

Watchers का परिचय

जब भी data का एक piece बदले एक watcher आपका code चलाता है, जो saving या fetching जैसे side effects के लिए useful है।

In this page:

  1. Watchers
Syntax
markup
export default {
  watch: {
    property(newValue, oldValue) {
      // react to the change
    }
  }
}

Watchers

watch option एक property name को एक function से map करता है जो new और old values receive करता है। Watchers बदलाव पर asynchronous या expensive reactions के लिए suit करते हैं, जबकि computed derived values के लिए suit करता है। आप quotes इस्तेमाल करके nested paths watch कर सकते हैं, जैसे "user.name"।

Note: जब आपको बस एक derived value चाहिए computed prefer करें।

उदाहरण: Watchers

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="q = 'vue'">Search vue</button>
  <p>Query: {{ q }} | History: {{ history.join(", ") }}</p>
</div>
<script>
  Vue.createApp({
    data() { return { q: "", history: [] }; },
    watch: { q(newVal, oldVal) { this.history.push(`"${oldVal}" -> "${newVal}"`); } },
  }).mount("#app");
  document.querySelector("button").click();
  Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: Search vueQuery: vue | History: "" -> "vue"
console: Query: vue | History: "" -> "vue"
-->
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. जहाँ computed काफी होता वहाँ एक watcher इस्तेमाल करना
  2. यह भूल जाना कि old value available है
  3. watched value बदलकर infinite loops बनाना
चैप्टर सारांश
  • watch changes पर react करता है
  • New और old values receive करता है
  • Side effects के लिए अच्छा है
  • Derived data के लिए Computed बेहतर है
🔒

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.