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>
运行示例 »