Skip to content

Vue2 中 ref 的使用

ref 是什么

ref 被用来给 DOM 元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs 对象上。

如果在普通的DOM 元素上使用,引用指向的就是 DOM 元素; 如果用在子组件上,引用就指向组件实例。

获得了引用信息,那么我们就可以操作元素或者组件了。

为什么使用 ref

通过定义我们知道了ref的作用注册引用,并通过$refs去获取该引用的DOM元素

也就是说在 vue 中要是操作 DOM 元素推荐使用$refs 这种方式,可以提高性能。

还有一点需要注意,ref 是在页面渲染完成后才被创建的

我们可以在 vue 的 mounted这个钩子函数中获取实例,因为在该函数页面已经被渲染完成。

ref 和 refs 的 关系

  • this.$refs 返回了一个对象,包含当前页面的所有 ref引用名称

  • ref 用于定义引用名称

怎么使用

this.$nextTick 这个函数的作用就是等页面加载完,一般配合 ref 使用

html
<div id="app">
  <a ref="a" href="http://www.w3school.com.cn">设置 DOM 元素的 ref</a>
  <HelloWorld ref="helloWorld" msg="Hello Vue in CodeSandbox!" />
</div>

methods: { init() { this.$ console.log("子组件:", this.$refs.helloWorld);
this.$nextTick(function(){ this.$refs.a.href = "www.baidu.com";
console.log("通过 ref 修改 DOM 元素:", this.$refs.a);
this.$refs.helloWorld.printHello(); }) }, },