Skip to content

What Is ref in Vue?

In Vue, the ref attribute creates references to components or DOM elements. It gives the JavaScript part of a Vue application direct access to a specific DOM element or component in the template — an alternative to traditional DOM queries that keeps you inside Vue's system.

Using ref

  1. Accessing DOM elements: add a ref attribute to an element in the template and reach it through the Vue instance.
    Vue
    <template>
      <div ref="myDiv">Hello World!</div>
    </template>
    
    <script>
    export default {
      mounted() {
        console.log(this.$refs.myDiv);
        // Gives access to the DOM element
      },
    };
    </script>
  2. Accessing components: add a ref to a child component to reach its instance, its methods and its data.
    VueCode fragment
    <ChildComponent ref="myComponent" />
    
    <script>
    export default {
      methods: {
        doSomething() {
          this.$refs.myComponent.someMethod();
          // Calls a method on ChildComponent
        },
      },
    };
    </script>

Things to know

  • $refs is an object on the Vue instance that gives access to elements marked with ref. It is not reactive: changes to $refs are not tracked by Vue.
  • A ref is set when the component or element is created and is available from mounted onwards; in beforeMount, $refs is still empty.
  • When you create many elements dynamically (for example with v-for), you can use the same ref name instead of a unique one for each; Vue collects the references into an array.

ref is especially useful when you need to work with the DOM directly or call methods of child components. Use it carefully so you do not work against Vue's reactivity and data flow.

Have a question about this article? Write to me