Tutorial

Communicating Between Recursive Components in Vue.js

Published on April 30, 2018
author

Alex Jover Morales

Communicating Between Recursive Components in Vue.js

In the Recursive Components in Vue.js post we’ve seen how to build a recursive Tree component, but we didn’t have to communicate any action across the tree. Let’s tackle that problem in this post.

What do you Mean by Communication?

Imagine that you want to check when a NodeTree from the previous article gets clicked-on, and communicate it to the outer component (the one who’s using the Tree component).

In Vue.js, upwards communication happens using custom events. But we’ve learned from Vue.js 1.x or Angular 1.x that having events across multiple levels is a bad practice and makes for a codebase that’s hard to reason about. That’s why, starting with Vue.js 2, custom events are only allowed on one child-to-parent level.

Knowing that, imagine a Tree like the following:

+ Folder 1
  + Folder 2
    + Folder 3
      + Folder 4
        + Folder 5

If we’d like to communicate a click event from Folder 5 using custom events, we’d have to emit an event up 5 times.

We can say a tree has infinite levels of depth, since we don’t know beforehand how many it has. For that reason, using custom events would make it unfeasible, inefficient and complex.

Solving Recursive Communication Using Props

Remember that we can use functions as props in Vue.js. It’s not a common pattern because, unlike with React, Vue.js has custom events for child-to-parent communication. But for cases like this one it really comes in handy.

Unlike emitting events at each level, this is much simpler and performant since we only need to pass down the same reference to the function.

Let’s add a handleClick property to the NodeTree.vue component, and use it for the click event:

NodeTree.vue
<template>
  <li class="node-tree">
    <span class="label" @click="handleClick(node)">{{ node.label }}</span>

    <ul v-if="node.children && node.children.length">
      <node
        v-for="child in node.children"
        :node="child"
        :handle-click="handleClick">
      </node>
    </ul>
  </li>
</template>

<script>
export default {
  name: "node",
  props: {
    node: Object,
    handleClick: Function
  }
};
</script>

Notice how we set its type as Function and we use it on the the label @click event and pass it down again to the children nodes :handle-click="handleClick".

Outer Communication

From the Tree.vue component, we still need to pass that function down to the root node.

Additionally, we must provide a way to handle the click from the outside (the component who uses Tree), and for this we can indeed use a custom event since it’s just one level up:

Tree.vue
<template>
  <div class="tree">
    <ul class="tree-list">
      <node-tree :node="treeData" :handle-click="handleClick"></node-tree>
    </ul>
  </div>
</template>

<script>
import NodeTree from "./NodeTree";

export default {
  props: {
    treeData: Object
  },
  methods: {
    handleClick (node) {
      this.$emit('node-click', node);
    }
  }
  components: {
    NodeTree
  }
};
</script>

As you can see, we added a handleClick method local to the Tree component, which is passed to the node-tree. This method emits an event with the node of data by using the $emit Vue instance method.

With that, we can handle the click from App.vue or any other external component, while keeping a nice API syntax by using @node-click on the template:

App.vue
<template>
  <div>
    <tree :tree-data="tree" @node-click="logClick"></tree>
  </div>
</template>

<script>
import Tree from "./Tree";

export default {
  data: () => ({
    // ...
  }),
  methods: {
    logClick(node) {
      console.log("Clicked: ", node);
    }
  },
  components: {
    Tree
  }
};
</script>

Wrapping Up

As you just saw, to fix the “infinite levels” communication problem, we’ve made use of a pattern that’s very common in the React community: passing a function down as a property. This allowed us to handle a click action easily on a recursive component while keeping it performant and easy to reason about.

Stay cool 🦄

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Alex Jover Morales

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more