Vue中this.$refs的使用
this.$refs在vue中ref可以以属性的形式添加给标签或者组件,
ref 写在标签上时:this.$refs.ipt 获取的是添加了ref="ipt"标签对应的dom元素,
ref 写在组件上时:this.$refs['component'] 获取到的是添加了ref="component"属性的这个组件
<template>
//给标签使用
<input type="text" ref="ipt"/>
//给组件使用
<comp-detail ref="component"></comp-detail>
<button @click="confirm">确定</button>
</template>
methods:{
confirm(){
console.log(this.$refs.ipt.value) //打印出输入框中的value值
this.$refs['component'].init() //调用组件comp-detail中的init()方法
}
}
$refs 是所有注册过 ref 的集合(对象);若是遍历的ref,则对应$refs是个数组集合
注意:$ refs不是响应式的,只在组件渲染完成之后才填充。所以想要获取DOM数据的更新要使用 this.$nextTick()
总结:
<!-- ref 写在标签上时:this.$refs.名字 获取的是标签对应的dom元素
ref 写在组件上(调用组件)时:这时候获取到的是 子组件(比如counter)的引用-->