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

ref/reactive गहराई से

ref single values और reassignments के लिए suit करता है जबकि reactive objects के लिए suit करता है, और हर एक की अपनी gotchas हैं।

In this page:

  1. ref/reactive In Depth
Syntax
markup
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

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"><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. #}
आम गलतियां
  1. एक reactive variable reassign करना
  2. .value भूल जाना
  3. 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:

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.