Vue $refs 物件
示例
在方法內部使用 $refs
物件來更改 <p>
標籤內的文字。
methods: {
changeVal() {
this.$refs.pEl.innerHTML = "Hello!";
}
}
執行示例 »
定義和用法
使用內建的 ref
屬性標記的 DOM 元素儲存在 $refs
物件中。
可以使用 this
關鍵字訪問 $refs
物件內的元素。
$refs
物件用於訪問 DOM 元素以讀取或操作它們,其方式類似於在原生 JavaScript 中使用 querySelector()
和 getElementById()
。
更多示例
示例 1
第一個 <p>
標籤的文字被複制到第二個 <p>
標籤中。
<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>
執行示例 »
示例 2
一個 <p>
元素獲得與輸入欄位中寫入的內容相同的文字。
<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>
執行示例 »
示例 3
按鈕顯示儲存在 $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>
執行示例 »
相關頁面
Vue 教程:Vue Template Refs
Vue 參考:Vue 'ref' 屬性