Vue3 ref Attribute

Vue3 内置属性Vue3 Built-in Attributes


refThe attribute is used to register reference information for elements or child components, so that DOM elements or component instances can be directly accessed in JavaScript code.


Basic Description

refIt is an important way to obtain DOM elements or component instances in Vue. It allows us to directly manipulate the DOM or call child component methods after the Vue instance is mounted.

  • Type: String | Function
  • Purpose: Access DOM elements or child component instances to perform operations such as focus control and method calls.

Basic Usage

1. Using ref in Options API

In the Options API, references registered by ref are stored in the component instance's$refsobject:

Example

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

<script>
export default {
  methods: {
    focusInput() {
// Access DOM elements via $refs
      this.$refs.inputField.focus()
    }
  }
}
</script>

2. Using ref in Composition API

In the Composition API, it is recommended to useuseTemplateRefto get template references:

Example

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

<script setup>
import { useTemplateRef } from 'vue'

// Create a reference matching the ref name in the template
const inputField = useTemplateRef('inputField')

function focusInput() {
// Directly access the DOM element
  inputField.value?.focus()
}
</script>

Use Cases

1. Accessing DOM Elements

Using ref, you can directly access DOM elements to perform operations such as focus control and value retrieval:

Example

<template>
  <div>
    <input type="text" ref="username" placeholder="Username" />
    <button @click="getValue">Get Value</button>
  </div>
</template>

<script>
export default {
  methods: {
    getValue() {
// Get the value of the input field
      const value = this.$refs.username.value
console.log('input value:', value)
    }
  }
}
</script>

2. Accessing Child Component Instances

Using ref, you can access a child component instance, call its methods, or access its data:

Example

<!-- Parent component -->
<template>
  <div>
    <child-component ref="childRef"></child-component>
    <button @click="callChildMethod">Call Child Component Method</button>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  components: {
    ChildComponent
  },
  methods: {
    callChildMethod() {
// Call the child component's method
      this.$refs.childRef.sayHello()
// Access the child component's data
console.log('Child component data:', this.$refs.childRef.message)
    }
  }
}
</script>

3. Functional ref

ref can also accept a function, which is called on every update, giving you full control over where the reference is stored:

Example

<template>
  <div>
    <input type="text" :ref="el => inputEl = el" />
    <button @click="focusInput">Focus</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputEl: null
    }
  },
  methods: {
    focusInput() {
      this.inputEl?.focus()
    }
  }
}
</script>

Notes

Timing of ref registration: Because ref itself is created from the result of the render function, it must be accessed after the component is mounted. Ifcreatedyou access it in a lifecycle hook,$refsit will still be an empty object.

Non-reactive:$refsIt is non-reactive, so it should not be used for data binding in templates. Only use it in JavaScript for DOM operations.

Avoid overusing ref: Operate the DOM and child components as much as possible through data-driven and event handling. Overusing ref will make the code difficult to maintain.

Example

<!-- Not recommended: accessing ref in created -->
<script>
export default {
  created() {
    console.log(this.$refs.inputField) // undefined
  },
  mounted() {
console.log(this.$refs.inputField) // can be accessed
  }
}
</script>

Usage with v-for

ref can also be used withv-forv-for, which creates an array containing all corresponding DOM elements or component instances:

Example

<template>
  <div>
    <div v-for="(item, index) in items" :key="item.id" :ref="el => setItemRef(el, index)">
      {{ item.name }}
    </div>
    <button @click="logRefs">Print all references</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
{ id: 1, name: 'Project 1' },
{ id: 2, name: 'Project 2' },
{ id: 3, name: '项目三' }
      ],
      itemRefs: []
    }
  },
  methods: {
    setItemRef(el, index) {
      if (el) {
        this.itemRefs[index] = el
      }
    },
    logRefs() {
console.log('All references:', this.itemRefs)
    }
  }
}
</script>

Vue3 内置属性Vue3 Built-in Attributes

Other Extensions