vue中的 ref 和 $refs

发布时间 2023-06-26 11:10:52作者: MARSHBAN

在Vue中,ref 是一个用于给元素或组件添加引用的特殊属性。通过在元素上添加 ref 属性,可以在Vue组件实例或父组件中通过引用访问该元素或组件的实例。

具体来说,ref 属性有两种用法:

1. 给普通元素添加引用:

<template>
  <div>
    <input ref="myInput" type="text">
    <button @click="focusInput">Focus Input</button>
  </div>
</template>

<script>
export default {
  methods: {
    focusInput() {
      this.$refs.myInput.focus();
    }
  }
}
</script>

在上面的例子中,我们给 <input> 元素添加了 ref="myInput",然后在组件的方法中可以通过 this.$refs.myInput 来访问该元素的实例。在 focusInput 方法中,我们通过 this.$refs.myInput.focus() 将焦点设置到输入框上。

2. 给组件添加引用:

<template>
  <div>
    <my-component ref="myComponent"></my-component>
    <button @click="callComponentMethod">Call Component Method</button>
  </div>
</template>

<script>
import MyComponent from './MyComponent.vue';

export default {
  components: {
    MyComponent
  },
  methods: {
    callComponentMethod() {
      this.$refs.myComponent.someMethod();
    }
  }
}
</script>

在这个例子中,我们使用 <my-component> 组件,并给它添加了 ref="myComponent"。然后在父组件的方法中,通过 this.$refs.myComponent 可以访问 <my-component> 组件的实例。在 callComponentMethod 方法中,我们通过 this.$refs.myComponent.someMethod() 调用了 <my-component> 组件的某个方法。

总之,ref 属性允许我们在Vue组件中通过引用访问元素或子组件的实例,从而可以直接操作元素或调用组件的方法。请注意,ref 引用是非响应式的,它只提供了对实例的直接引用,并不会触发数据的自动更新。