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(); }) }, },