رفرنس های تمپلیت (Template Refs)
«رفرنس تمپلیت (Template Ref)» یعنی آدرس دهی مستقیم به یک عنصر DOM. وقتی روی تگ HTML ویژگی ref می گذاری، آن عنصر بعداً از طریق شیء $refs در دسترس است. مثل صدا زدن هم کلاسی با اسمش!
رفرنس ها و شیء $refs
با ref روی تگ ها، همان عناصر داخل $refs ذخیره می شوند. سپس می توانی از داخل اسکریپت به آن ها دسترسی بگیری و مقدارشان را تغییر دهی.
<template>
<h1>Example</h1>
<p>Click the button to put \"Hello!\" as the text in the green p element.</p>
<button @click="changeVal">Change Text</button>
<p ref="pEl">This is the initial text</p>
</template>
<script>
export default {
methods: {
changeVal() {
this.$refs.pEl.innerHTML = "Hello!";
}
}
};
<\/script>
کپی متن با Template Refs
می خواهی متن از یک پاراگراف به دیگری برود؟ به سادگی با $refs مقدار را جابه جا کن.
<template>
<h1>Example</h1>
<p ref="p1">Click the button to copy this text into the paragraph below.</p>
<button @click="transferText">Transfer text</button>
<p ref="p2">...</p>
</template>
<script>
export default {
methods: {
transferText() {
this.$refs.p2.innerHTML = this.$refs.p1.innerHTML;
}
}
};
<\/script>
گرفتن مقدار ورودی با $refs
می توانی به ویژگی های داخلی عنصر برسی. مثلاً مقدار input را بخوانی و در پاراگراف بنویسی.
<template>
<h1>Example</h1>
<p>Start writing inside the input element, and the text will be copied into the last paragraph by the use of the '$refs' object.</p>
<input ref="inputEl" @input="getRefs" placeholder="Write something..">
<p ref="pEl"></p>
</template>
<script>
export default {
methods: {
getRefs() {
this.$refs.pEl.innerHTML = this.$refs.inputEl.value;
}
}
};
<\/script>
Template Ref همراه با v-for
اگر روی آیتم های v-for، ref بگذاری، داخل $refs یک آرایه می گیری. سپس عنصر دلخواه را با اندیس بردار.
<template>
<h1>Example</h1>
<p>Click the button to reveal the 3rd list element stored as an array element in the $refs object.</p>
<button @click="getValue">Get the 3rd list element</button><br>
<ul>
<li v-for="x in liTexts" ref="liEl">{{ x }}</li>
</ul>
<pre>{{ thirdEl }}</pre>
</template>
<script>
export default {
data() {
return {
thirdEl: " ",
liTexts: ["Apple", "Banana", "Kiwi", "Tomato", "Lichi"]
};
},
methods: {
getValue() {
this.thirdEl = this.$refs.liEl[2].innerHTML;
console.log("this.$refs.liEl = ", this.$refs.liEl);
}
}
};
<\/script>
<style>
pre {
background-color: lightgreen;
display: inline-block;
}
<\/style>
گام های عملی رفرنس های تمپلیت
- روی تگ، یک نام
refبگذار. - در اسکریپت، از
this.$refsاستفاده کن. - ویژگی یا متن عنصر را تغییر بده.
- با
v-for، آرایه رفرنس ها را مدیریت کن.
نکته: از رفرنس ها برای کارهای ضروری استفاده کن. بهتر است داده محور بمانی و فقط در موارد خاص سراغ DOM مستقیم بروی.
جمع بندی سریع
- هر
refوارد$refsمی شود. - می توانی متن یا ویژگی ها را تغییر دهی.
- با
v-for، آرایه رفرنس داری. - ساده نگه دار؛ اولویت با داده است.
مطالب مرتبط: درخواست HTTP، Teleport در Vue، و چرخه حیات کامپوننت ها. یکی از این ها را با کلیدواژه «رفرنس های تمپلیت» جستجو کن.