[Vuejs]-Vue.js components hierarchical relationship

1👍

Yes, there is are at least 2 native approaches of figuring out if a DOM node is a parent of another node:

1.This one is cross-browser and it implies using the DOMNode.parentNode

function isChildOf(parent, child) {
     const node = child.parentNode;
     while (node) {
         if (node == parent) {
             return true;
         }
         node = node.parentNode;
     }
     return false;
}

2.Much more elegant way is to use directly the DOMNode.contains method. This returns directly a boolean.

parentNode.contains(childNode);

That was in pure JavaScript, but in Vue you will have to use the refs property to get the node and then just to the same as above.
So the code can be something along this lines:

<template>
  <div id="app" ref="app">
    <HelloWorld msg="Hello Vue!" ref="hello"/>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld
  },
  mounted() {
    // Note: the root is directly a DOM element.
    const appNode = this.$refs.app;
    const helloNode = this.$refs.hello.$el;

    console.log(this.containsChild(appNode, helloNode)); // TRUE
  },
  methods: {
    containsChild(parent, child) {
      return parent.contains(child);
    }
  }
};
</script>

Leave a comment