DEV Community

Ahmet Meliksah Akdeniz
Ahmet Meliksah Akdeniz

Posted on • Edited on

Vue.js Basics Part 4 | Lifecycle and Template Refs

Today, I will be talking about ref attribute in Vue.js.

This is part 4 of my Vue.js Basics series, to read part 2, please click here (spoiler! Part 3 is about computed property)

We use ref attribute when we need to manually work with the DOM. Perhaps, the most common use case is forms, especially when we want to focus on input when the page is 'mounted' (loaded).

'Mounted' is one the lifecycle hooks in Vue. What are lifecycle hooks? In short, each Vue component goes through a series of steps when it's created. Some of the most common ones are updated and unmounted.

Why lifecycle hoooks? Because they give us opportunities to add our own code at specific stages (when page is loaded/rendered, updated, unmounted and e.g.).

What does mounted attribute do? mounted hook is used after the component has finished the initial rendering. That means whatever we put inside mounted will be run immediately after the component 'mounts' (after first render).

Let's get back to ref. So, how to use it?
Like so:

<template>
  <p ref="p">hello</p>
</template>
Enter fullscreen mode Exit fullscreen mode

First of all, add ref attribute to element that you want to reference. ref="p", 'ref=' indicates reference, and 'p' indicates how you refer to it. I will throw in the code below, so it will be more understandable

<script>
export default {
  mounted() {
    this.$refs.p.innerHTML = "yooo"
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

In mounted hook (and in any lifecycle hooks), we have access to objects using the this keyword, otherwise, Vue won't know what we're referring to. this.$refs.p.innerHTML = "yooo" with this line of code, we go to ref and choose p (remember ref="p") and change its innerHTML value to something else.

To sum it up, today we briefly talked about lifecycle hooks and template reference (ref) in Vue.js

Top comments (0)