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>