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

toRef() का उपयोग

toRef एक ref बनाता है जो एक reactive object की एक property से linked रहता है।

In this page:

  1. toRef()
Syntax
markup
import { reactive, toRef } from 'vue';
const state = reactive({ property: value });
const propRef = toRef(state, 'property');

toRef()

toRef(obj, "key") एक ref return करता है जिसकी value source की वह property पढ़ती और लिखती है। Changes दोनों तरफ flow होते हैं। toRefs हर property के लिए वही करता है, जो आपको reactivity खोए बिना एक reactive object destructure करने देता है, और composables से state return करते वक्त handy है।

Note: जब आप एक reactive object की properties destructure या return करना चाहें toRefs इस्तेमाल करें।

उदाहरण: toRef()

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>{{ name }} / {{ user.name }}</p>
</div>
<script>
  Vue.createApp({
    setup() {
      const user = Vue.reactive({ name: "Ada", age: 36 });
      const name = Vue.toRef(user, "name");
      name.value = "Grace";
      const { age } = Vue.toRefs(user);
      age.value++;
      console.log("linked back:", user.name, user.age);
      return { user, name };
    },
  }).mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: Grace / Grace
console: linked back: Grace 37
-->
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 objects को सीधे destructure करना
  2. यह उम्मीद करना कि toRef value copy करेगा
  3. resulting ref पर .value भूल जाना
चैप्टर सारांश
  • toRef एक property से link करता है
  • toRefs सारी properties से link करता है
  • Changes दोनों तरफ flow होते हैं
  • Destructure करते वक्त reactivity रखता है
🔒

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.