Watchers का परिचय
जब भी data का एक piece बदले एक watcher आपका code चलाता है, जो saving या fetching जैसे side effects के लिए useful है।
In this page:
Syntax
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
<!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. #}
आम गलतियां
- जहाँ computed काफी होता वहाँ एक watcher इस्तेमाल करना
- यह भूल जाना कि old value available है
- 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: