首页 > 技术文章 > Vue中 $ref 的用法

wu50401 2019-01-03 11:06 原文

说明:vm.$refs 一个对象,持有已注册过 ref 的所有子组件(或HTML元素)
使用:在 HTML元素 中,添加ref属性,然后在JS中通过vm.$refs.属性来获取
注意:如果获取的是一个子组件,那么通过ref就能获取到子组件中的data和methods
添加ref属性
<div id="app">
<h1 ref="h1Ele">这是H1</h1>
<hello ref="ho"></hello>

<button @click="getref">获取H1元素</button>
</div>

获取注册过 ref 的所有组件或元素
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);// 获取组件的方法
}
}

推荐阅读