Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Accessing DOM Elements and Components with ref and Using this.$nextTick in Vue 2.x

Tech 1

ref References

ref is Vue's built-in mechanism for getting references to DOM elements or component instances without relying on external libraries like jQuery.

Every Vue component instance includes a $refs object that stores all matched references. By default, $refs is an empty object before any references are registered.

Referencing DOM Elements

To get a reference to a plain DOM element, add the ref attribute to the element with your chosen reference name:

<!-- Assign a custom reference name to the target DOM element -->
<div ref="contentDiv">Sample element content</div>
methods: {
  updateElementStyle() {
    // Access the target DOM node via this.$refs.<reference-name>
    this.$refs.contentDiv.style.color = 'red';
  }
}

Referencing Component Instances

You can also use ref to get a reference to an entire child component instance, which lets you access its methods and internal data directly:

<!-- Add the ref attribute to the child component -->
<CounterWidget ref="childCounter"></CounterWidget>

<script>
  // If the CounterWidget component exposes an increment method,
  // you can call it directly after accessing the component instance
  // this.$refs.childCounter returns the full instance of the child component
  this.$refs.childCounter.incrementCount();
</script>

The this.$nextTick(cb) Method

Core Purpose

The $nextTick(cb) method defers execution of the input callback cb until after the next DOM update cycle. In plain terms, it waits until Vue has finished updating the DOM tree to reflect your latest data changes, then runs your callback. This guarantees that your code can itneract with the most up-to-date version of the DOM.

Practical Use Case Example

A common scenario where $nextTick is required is toggling dynamic UI elements that need immediate interaction. For example: a comment input that only appears after clicking a button, and needs to automatically receive focus when it opens. The initial state has the button visible and the input hidden. When the input loses focus, it hides again and the button reappears.

We control visibility with a boolean flag and v-if, but we run into a problem: immediaetly after flipping the boolean to show the input, the input has not been added to the DOM yet. Trying to call focus on it at this point will fail.

Using the updated lifecycle hook also doesn't work, because updated triggers after every DOM update, including when the input is hidden, which will cause errors trying to focus a non-existent element.

$nextTick solves this cleanly, as shown below:

<template>
  <div class="comment-container">
    <input 
      type="text" 
      v-if="showCommentInput" 
      @blur="hideInput" 
      ref="commentInput" 
    />
    <button v-else @click="showInput">Write Comment</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // Controls visibility toggle between input and button
      // Default: false = show button, hide input
      showCommentInput: false
    }
  },
  methods: {
    showInput() {
      // Update data to trigger DOM change and show input
      this.showCommentInput = true;
      // Defer focus call until after DOM finishes updating
      this.$nextTick(() => {
        this.$refs.commentInput.focus();
      });
    },
    hideInput() {
      this.showCommentInput = false;
    }
  }
}
</script>
Tags: Vue 2.x

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.