Vue 'ref' 屬性
示例
使用 ref
屬性更改 <p>
標籤內的文字
<div id="app">
<p ref="pEl">初始文字。</p>
<button v-on:click="changeText">更改文字</button>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script type="module">
const app = Vue.createApp({
methods: {
changeText(){
this.$refs.pEl.innerHTML = "Hello!";
}
}
})
app.mount('#app')
</script>
自己動手試一試 »
更多示例請參見下方。
定義和用法
ref
屬性用於標記 <template>
中的元素,以便它們可以在 <script>
內的 $refs
物件中訪問。
我們可以使用 ref
屬性和 $refs
物件,作為純 JavaScript 中方法(如 getElementById()
或 querySelector()
)的替代方案。
如果用 v-for
建立的 HTML 元素帶有 ref
屬性,則生成的 DOM 元素將作為陣列新增到 $refs
物件中,如本示例所示。
更多示例
示例 1
第一個 <p>
標籤內的文字被更改。
<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><br>
<p ref="pEl" id="pEl">This is the initial text</p>
</template>
<script>
export default {
methods: {
changeVal() {
this.$refs.pEl.innerHTML = "Hello!";
}
}
};
</script>
<style>
#pEl {
background-color: lightgreen;
display: inline-block;
}
</style>
執行示例 »
示例 2
第一個 <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>
執行示例 »
示例 3
一個 <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>
執行示例 »
示例 4
按鈕顯示儲存在 $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 v-for 指令
Vue 參考:Vue $refs 物件