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

$refs का उपयोग

Template refs आपको एक DOM element या child component instance तक direct access देते हैं।

In this page:

  1. $refs
Syntax
markup
<input ref="name">

mounted() {
  this.$refs.name.focus();
}

$refs

एक element या component में ref="name" add करें और mount होने के बाद इसे this.$refs.name से पढ़ें। यह एक input focus करने या एक child का method call करने जैसी चीज़ों के लिए escape hatch है। refs इस्तेमाल करके ऐसी state बदलने से बचें जो props के जरिए flow कर सकती थी।

Note: Refs सिर्फ component mount होने के बाद available हैं।

उदाहरण: $refs

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">
  <input ref="box" value="focus me">
  <child-counter ref="child"></child-counter>
</div>
<script>
  const app = Vue.createApp({
    mounted() {
      this.$refs.box.focus();
      this.$refs.child.bump();
      console.log("input focused:", document.activeElement === this.$refs.box);
      console.log("child count via ref:", this.$refs.child.n);
    },
  });
  app.component("child-counter", {
    data() { return { n: 0 }; },
    methods: { bump() { this.n++; } },
    template: "<p>n = {{ n }}</p>",
  });
  app.mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: n = 1
console: input focused: true
console: child count via ref: 1
-->
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. mounted से पहले refs पढ़ना
  2. props और events की बजाय refs इस्तेमाल करना
  3. यह भूल जाना कि v-for के अंदर refs arrays हैं
चैप्टर सारांश
  • ref attribute एक reference register करता है
  • mount के बाद this.$refs पढ़ें
  • Focus और imperative calls के लिए अच्छा
  • Data के लिए props और events prefer करें
🔒

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.