我们可以进一步研究添加到 $refs 对象的 HTML 元素,以访问我们想要的任何属性。
<p> 元素获取与输入字段中写入的内容相同的内容。
App.vue:
<template>
<h1>示例</h1>
<p>开始在输入元素内写入,文本将通过使用"$refs"对象复制到最后一段。</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>
运行示例 »
使用 v-for 创建的带有 ref 属性的 HTML 元素将作为数组添加到 $refs 对象中。
该按钮显示作为数组元素存储在 $refs 对象内的第三个列表元素。
App.vue:
<template>
<h1>示例</h1>
<p>单击该按钮可显示作为数组元素存储在 $refs 对象中的第三个列表元素。</p>
<button @click="getValue">获取第3个列表元素</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>
运行示例 »
相关
视频
RELATED VIDEOS
科技资讯
1
2
3
4
5
6
7
8
9
精选课程
共5课时
17.3万人学习
共49课时
77.4万人学习
共29课时
62万人学习
共25课时
39.5万人学习
共43课时
71.2万人学习
共25课时
61.9万人学习
共22课时
23.1万人学习
共28课时
34.1万人学习
共89课时
125.7万人学习