vue $refs

在Vue中,$refs 是一个对象,用于访问在模板中通过 ref 属性注册的 DOM 元素或子组件实例。这是Vue提供的一种非常方便的方式来直接访问和操作DOM元素或子组件。

使用场景

  1. 直接访问DOM元素:当需要直接操作DOM元素时(比如,设置焦点、触发原生事件等),可以使用 ref 来注册这个元素,并通过 this.$refs 来访问它。
  2. 访问子组件实例:如果组件内部使用了其他组件,并且需要直接访问这些子组件的方法或数据,也可以通过 ref 来注册子组件,并通过 this.$refs 来访问子组件的实例。

示例

访问DOM元素

<template>  
  <div>  
    <input ref="myInput">  
    <button @click="focusInput">Focus the input</button>  
  </div>  
</template>  
  
<script>  
export default {  
  methods: {  
    focusInput() {  
      // 访问DOM元素并设置焦点  
      this.$refs.myInput.focus();  
    }  
  }  
}  
</script>

访问子组件实例

<!-- ChildComponent.vue -->  
<template>  
  <div>  
    <p>{{ message }}</p>  
  </div>  
</template>  
  
<script>  
export default {  
  data() {  
    return {  
      message: 'Hello from Child'  
    }  
  },  
  methods: {  
    updateMessage(newMessage) {  
      this.message = newMessage;  
    }  
  }  
}  
</script>
<!-- ParentComponent.vue -->  
<template>  
  <div>  
    <ChildComponent ref="childComponent" />  
    <button @click="updateChildMessage">Update Child Message</button>  
  </div>  
</template>  
  
<script>  
import ChildComponent from './ChildComponent.vue';  
  
export default {  
  components: {  
    ChildComponent  
  },  
  methods: {  
    updateChildMessage() {  
      // 访问子组件实例并调用其方法  
      this.$refs.childComponent.updateMessage('New message from Parent');  
    }  
  }  
}  
</script>

注意事项

  • $refs 只在组件渲染完成后填充,并且它们不是响应式的。这意味着不能在模板中或计算属性中通过 $refs 访问DOM元素或子组件实例。
  • 如果 ref 是在 v-for 循环中使用的,$refs.name 将是一个包含多个元素的数组,而不是单个元素。
  • $refs 的值会在组件的 $mount 生命周期钩子被调用之后被填充,并且当组件被销毁时,其 $refs 也会被销毁。
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值