How to call a child function using refs in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to directly access child functions on parent events in Vue.js using the ref attribute.

There are other ways to access child functions e.g. using events and props. But in this example, we’ll access child functions using refs.

Let’s start by creating our parent component. We’ll call it Header.vue. It will be a layout component, which will have a site navigation bar, logo and search.

<div id="app">
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Navbar</a>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
       <search ref="search" />

Hi, I'm Renat 👋


Note the <search ref="search" /> component. By giving our child component a ref attribute we can now use $refs to access search component’s functions.

If the search component has a function that makes a search form full width we can access it using:


We can also access data() object to change the component’s values:

this.$ = []

It’s super easy to access child functions and data in Vue.js.

If you find this post useful, please let me know in the comments below. 
Renat Galyamov

Want to share this with your friends?

PS: Make sure you check other Vue.js tutorials, e.g. how to set base URL and global variables in Vue.js or how to use v-show.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment