this.$refs和this.$ref的区别

this.$refs 和 this.$ref 有以下区别:
this.$refs:

  • 是一个对象,包含了当前组件的所有子组件(或DOM元素)的引用
  • 需要在子组件(或DOM元素)上指定 ref 属性才能获取到引用
  • 可以在模板或渲染函数中访问 this.$refs

this.$ref:

  • 是一个单个引用,对应当前组件的父组件(或DOM元素)
  • 不需要指定任何 ref 属性
  • 只能在渲染函数中通过 this.$parent.$ref 访问

例子:
父组件:

1
<child-component ref="child"></child-component>

子组件:

1
2
3
4
5
export default {
mounted() {
console.log(this.$parent.$ref === 'child') // true
}
}

父组件:

1
2
<div ref="parent"></div> 
<child-component ref="child"></child-component>

子组件:

1
2
3
4
5
6
export default {
mounted() {
console.log(this.$refs.parent) // DOM element
console.log(this.$refs.child) // Child component instance
}
}

总结:

  • this.$refs 用于获取子组件(或DOM元素)的引用,需要在子组件上指定 ref 属性
  • this.$ref 用于在子组件中获取父组件的引用,不需要指定任何 ref 属性
  • this.$ref 只能在子组件的渲染函数中访问,通过 this.$parent.$ref
  • 区分 this.$refs 和 this.$ref 的用途和访问位置,可以更好地把握组件间的通信

this.$refs和this.$ref的区别
http://oowatermelon.github.io/OoWaterMelonS/2023/04/20/this-refs和this-ref的区别/
作者
OoWaterMelonS Shao
发布于
2023年4月20日
许可协议