$refs का उपयोग
Template refs आपको एक DOM element या child component instance तक direct access देते हैं।
In this page:
Syntax
<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
<!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. #}
आम गलतियां
- mounted से पहले refs पढ़ना
- props और events की बजाय refs इस्तेमाल करना
- यह भूल जाना कि 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: