$refs
Misol
<p> tegi ichidagi matnni o‘zgartirish uchun metod ichida $refs obyektidan foydalanish.
methods: {
changeVal() {
this.$refs.pEl.innerHTML = "Hello!";
}
}
Misolni ishga tushirish »
Ta’rif va qo‘llanilishi
O‘rnatilgan ref atributi bilan belgilangan DOM elementlari $refs obyektida saqlanadi.
$refs obyekti ichidagi elementlarga this kalit so‘zi orqali murojaat qilish mumkin.
$refs obyekti DOM elementlariga murojaat qilib, ularni o‘qish yoki o‘zgartirish uchun ishlatiladi — xuddi oddiy JavaScript’da querySelector() va getElementById() ishlatilgani kabi.
Ko‘proq misollar
1-misol
Birinchi <p> tegidagi matn ikkinchi <p> tegiga ko‘chiriladi.
<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>
Misolni ishga tushirish »
2-misol
<p> elementi input maydoniga yozilayotgan matn bilan bir xil tarkibni oladi.
<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>
Misolni ishga tushirish »
3-misol
Tugma $refs obyekti ichida massiv elementi sifatida saqlangan uchinchi ro‘yxat elementini ko‘rsatadi.
<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>
Misolni ishga tushirish »
Tegishli sahifalar
Vue darsligi: Vue shablon reflari (template refs)
Vue ma’lumotnomasi: Vue ref atributi
W3Schools Pathfinder
Yutuqlaringizni kuzating – bu bepul!
