[Vuejs]-Detect from component if it is within certain DOM parent

0👍

You might want to use $parent as specified in the Vue documentation.
For example, you can get the name of the parent component by accessing to its “$options.name” property.

Example:

App.vue

<template>
  <div id="app">
    <ParentComponent>
      <ChildComponent />
    </ParentComponent>
  </div>
</template>

<script>
import ParentComponent from './components/ParentComponent'
import ChildComponent from "./components/ChildComponent";

export default {
  name: 'App',
  components: {
    ParentComponent,
    ChildComponent
  }
}
</script>

<style>
</style>

ParentComponent.vue

<template>
  <div>
    <p>I'm a parent component.</p>
    <slot></slot>
  </div>
</template>

<script>

export default {
  name: "ParentComponent",
  props: {},
  computed: {}
};
</script>

<style scoped>
</style>

ChildComponent.vue

<template>
  <div>
    <p>Parent name: {{componentName}}</p>
    <p>I'm inside a ParentComponent? {{componentName === "ParentComponent" ? "Yes!" : "No."}}</p>
  </div>
</template>

<script>
export default {
  name: "ChildComponent",
  computed: {
    componentName() {
        // We get the parent name from the $options.name property of our parent 
        // component
        return this.$parent.$options.name
    }
  }
};
</script>

<style scoped>
</style>

NOTE You can also access to other properties on the parent component by using the $parent property. Try it out!

Leave a comment