Vue.js Access Dom Nodes using Refs

Published on December 23, 2019 32 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

In this topic, I’m going to share how to access dom nodes using refs in Vue.js.

Meaning of Refs

Ref is used to register or indicate a reference to the HTML element or child element in the template. Syntax:

<!-- template -->
ref='fieldID'

<!-- script -->
this.$refs.fieldID.METHOD

Implement of Refs

We can indicate HTML element via ref. Let’s set focus on a search box input field using ref.

<template>
  <div id="app">
    <label for="search">Search:</label>
    <input type="text" id="search" name="search" ref="searchbox">
  </div>
</template>

We’ve identified the search field by ref id searchbox. Let’s focus this:

<script>
export default {
  name: 'app',
  data() {
    return {
    }
  },
  mounted: function() {
    this.$refs.searchbox.focus()
  }
}
</script>

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *