Vue 模板引用
Vue 的模板引用用於引用特定的 DOM 元素。
當 ref
屬性被設定在 HTML 標籤上時,生成的 DOM 元素將被新增到 $refs
物件中。
我們可以使用 ref
屬性和 $refs
物件作為純 JavaScript 中 getElementById() 或 querySelector() 等方法的替代方案。
'ref' 屬性和 '$refs' 物件
帶有 ref
屬性的 HTML 標籤將被新增到 $refs
物件中,並且可以在後面的 <script>
標籤中訪問到。
示例
一個 <p>
元素的文字被更改。
App.vue
:
<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>
執行示例 »
下面的另一個示例展示瞭如何使用 $refs
物件將一個標籤的值複製到另一個標籤中。
示例
第一個 <p>
標籤的文字被複制到第二個 <p>
標籤中。
App.vue
:
<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' 獲取輸入值
我們可以深入訪問新增到 $refs
物件中的 HTML 元素,以訪問我們想要的任何屬性。
示例
一個 <p>
元素獲得與輸入欄位中寫入的內容相同的文字。
App.vue
:
<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>
執行示例 »
'ref' 與 v-for 結合使用
使用 v-for
建立的帶有 ref
屬性的 HTML 元素將被新增為陣列形式到 $refs
物件中。
示例
按鈕顯示儲存在 $refs
物件內的陣列元素中的第三個列表項。
App.vue
:
<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>
執行示例 »