1

I would like to set a class to a child component based on in which parent component I am using it. So, for example, I have a dropdown menu, that I would like to use in more components, but I would like to give it a different class based on in which component I am using it. Something like this, parent component top-bar:

<dropdown-menu :menu="link" :parent:'top-bar'></dropdown-menu>

And then in the dropdown-menu component:

<div class="dropdown" :class="{ parent: parent }">

<script>
  export default {
    name: 'dropdown-menu',
    props: ['parent'],

But, that is not working, how can I do this?

1
  • Not sure if this is the only problem but i believe :parent:'top-bar' should be :parent='top-bar'. Commented Nov 2, 2017 at 8:23

1 Answer 1

2

You had a typo :parent:'top-bar' -> :parent='top-bar' and your class binding would always pass the 'parent' string as a class. Learn more here.

I also made a small working example:

Vue.component('parent1', {
  template: '<div><dropdown-menu :menu="link" :parent="top_bar"></dropdown-menu></div>',
  data () {
      return {
          link: 'a link',
          top_bar: 'parent1'
      }
  }
});

Vue.component('parent2', {
  template: '<div><dropdown-menu :menu="link" :parent="top_bar"></dropdown-menu></div>',
  data () {
      return {
          link: 'another link',
          top_bar: 'parent2'
      }
  }
});

Vue.component('dropdown-menu', {
  template: '<div class="dropdown" v-bind:class="parent">{{ menu }}</div>',
  props: ['parent', 'menu']
});

var vm = new Vue({
  el: '#app'
});
.parent1 {
    color: red;
}

.parent2 {
    color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>

<div id="app">
  <parent1></parent1>
  <parent2></parent2>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.