Blog>
Snippets

Conditional Refs and Vue's `nextTick`

Provide a code example of attaching a ref conditionally inside a `v-if` directive and using Vue's `nextTick` to interact with the element after the DOM has updated.
// In this Vue component example, we use `v-if` to conditionally attach a ref to an input element
// and `nextTick` to focus on it after it has been rendered.

new Vue({
  el: '#app',
  data: {
    showInput: false // Initially, the input is not shown
  },
  methods: {
    toggleInputVisibility() {
      this.showInput = !this.showInput;
      // Use Vue.nextTick to wait for the DOM to update
      this.$nextTick(() => {
        if (this.showInput) {
          // Focus the input after it is displayed
          this.$refs.myInputRef.focus();
        }
      });
    }
  }
});
In this Vue component, the `toggleInputVisibility` method toggles `showInput` data property. Vue's `nextTick` is used inside this method to wait until after the DOM updates to focus the input element if it's visible.
<!-- The corresponding HTML for the Vue component with the conditional ref inside the template -->

<div id="app">
  <button @click="toggleInputVisibility">Toggle Input Visibility</button>
  <div v-if="showInput">
    <!-- Conditionally rendered input with a ref -->
    <input ref="myInputRef" type="text" />
  </div>
</div>
This is the HTML template for the Vue component which includes a button to toggle the visibility of an input element. The `ref` is conditionally attached to the input element using `v-if` directive.