Vue2实例property--$refs

107 阅读1分钟

ref引用简介

  • ref 用来辅助开发者在不依赖于 jQuery 的情况下获取 DOM 元素或组件的引用
  • 本质: 对象
  • 每个组件实例都包含 $refs对象,持有注册过 ref attributeDOM 元素和组件实例
  • 组件的 $refs 默认是一个空对象

image-20221116174235550.png

基本使用

  • 绑定一个 ref 引用
 <h1 ref="myh1">App 根组件</h1>

image-20221116174341319.png

 methods: {
   showThis() {
     console.log(this.$refs.myh1);
   },
 }

image-20221116174419321.png

  • 操作 DOM 元素,修改样式
 <h1 ref="myh1">App 根组件</h1>
 <button @click="changeColor">改变颜色</button>
 methods: {
   changeColor() {
     this.$refs.myh1.style.color = "red";
   },
 }

image-20221116174544194.png

组件引用

  • 使用 ref 引用页面上的组件实例
 <Child ref="child" />

image-20221116174903010.png

  • 修改组件数据
 <button @click="resetChild">修改组件样式</button>
 methods: {
   resetChild() {
     this.$refs.child.user.lastName = "Kobe";
   }
 }

image-20221116175212291.png

注意:当 refv-for 一起使用,得到的 ref对象是一个包含对应数据源的子组件数组

 <Child ref="child" v-for="i in 4" :key="i" />

image-20221116175722288.png

ref属性总结

  1. 用来给元素或子组件注册引用信息(id的替代者)
  1. 绑定在 html 标签上获取的是真实 DOM 元素,绑定在组件标签上是组件实例对象
  1. 使用方式:

    • 注册: <h1 ref="xxx">.....</h1><Left ref="xxx" />
    • 获取: this.$refs.xxx

注意: $refs 只会在组件渲染完成之后生效,并且不是响应式的

  • 这仅作为一个用于直接操作 DOM 或子组件的入口
  • 避免在模板或计算属性中访问 $refs