ref 有三种用法:
1、ref 加在普通的元素上,用this.$refs.(ref值) 获取到的是dom元素
2、ref 加在子组件上,用this.$refs.(ref值) 获取到的是组件实例,可以使用组件的所有方法。在使用方法的时候直接this.$refs.(ref值).方法() 就可以使用了。
3、如果通过v-for 遍历想加不同的ref时记得加 :号,即 :ref =某变量 ;
注意:
ref需要在dom挂载后才能获取到,否则undefined,在使用的时候确保dom已经渲染完成。比如在生命周期 mounted(){} 钩子中调用,或者在 this.$nextTick(()=>{}) 中调用。
2、如果ref 是循环出来的,有多个重名,那么ref的值会是一个数组 ,此时要拿到单个的ref 只需要循环就可以了。
案例:
<div id="app">
<h1 ref="h1Ele">这是H1</h1>
<hello ref="ho"></hello>
<button @click="getref">获取H1元素</button>
</div>
methods: {
getref() {
// 表示从 $refs对象 中, 获取 ref 属性值为: h1ele DOM元素或组件
console.log(this.$refs.h1Ele.innerText);
this.$refs.h1ele.style.color = 'red';// 修改html样式
console.log(this.$refs.ho.msg);// 获取组件数据
console.log(this.$refs.ho.test);// 获取组件的方法
}
}