简体   繁体   中英

Vue - bind a css class name with a property value

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM