ref/reactive गहराई से
ref single values और reassignments के लिए suit करता है जबकि reactive objects के लिए suit करता है, और हर एक की अपनी gotchas हैं।
In this page:
Syntax
const count = ref(0); // access with .value in script
count.value++;
const state = reactive({ count: 0 }); // access properties directly
state.count++;
ref/reactive In Depth
ref primitives और objects के लिए काम करता है और script में हमेशा .value चाहिए। reactive objects को proxy करता है और अगर आप इसे reassign या destructure करें reactivity खो देता है।
एक common pattern simple values के लिए ref और grouped state के लिए reactive है, या consistency के लिए हर जगह ref। isRef, unref, और toRaw edge cases में मदद करते हैं।
Note:
कई teams consistent behaviour के लिए हर जगह ref चुनती हैं।
उदाहरण: ref/reactive in depth
<!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"><p>{{ a }} {{ obj.x }} {{ info }}</p></div>
<script>
Vue.createApp({
setup() {
const a = Vue.ref(1);
const obj = Vue.reactive({ x: 10 });
const { x } = obj; // plain copy: no longer reactive
obj.x = 11;
const objRef = Vue.ref({ y: 1 });
objRef.value.y++;
const info = `x copy=${x}, obj.x=${obj.x}, isRef=${Vue.isRef(a)}, unref=${Vue.unref(a)}, y=${objRef.value.y}`;
console.log(info);
return { a, obj, info };
},
}).mount("#app");
</script>
</body>
</html>
<!-- Output:
Rendered: 1 11 x copy=10, obj.x=11, isRef=true, unref=1, y=2
console: x copy=10, obj.x=11, isRef=true, unref=1, y=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. #}
आम गलतियां
- एक reactive variable reassign करना
- .value भूल जाना
- reactive objects destructure करना
चैप्टर सारांश
- ref को .value चाहिए
- reactive objects को proxy करता है
- reactive reassign या destructure करना इसे तोड़ देता है
- unref और isRef मदद करते हैं
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: