Vue ref 属性
实例
使用 ref
属性更改 <p>
标记内的文本:
<div id="app">
<p ref="pEl">Initial text.</p>
<button v-on:click="changeText">Change text</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
对象访问这些元素。
我们可以使用 Vue 中的 ref
属性和 $refs
对象来替代普通 JavaScript 中的方法,如 getElementById()
或 querySelector()
。
如果使用 v-for
创建的 HTML 元素具有 ref
属性,则生成的 DOM 元素将作为数组添加到 $refs
对象中,如本例所示:
实例
<ul>
<li v-for="x in liTexts" ref="liEl">{{ x }}</li>
</ul>
更多实例
实例 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>