RJ.Hwang
RJ.Hwang

Reputation: 1913

How to set default class on component if user not set class?

A custom component need to set a default className if the caller not define it. How to do this?

The component :

Vue.component('the-component', { template: 'div class="default-class">...</div>', ... });

<the-component></the-component> render to div class="default-class"></div> is what I want.

but <the-component :class='user-class'></the-component>
actual render to div class="user-class default-class"></div>
but I wanna div class="user-class"></div>.

Upvotes: 1

Views: 69

Answers (1)

Dan Gamble
Dan Gamble

Reputation: 4155

I'm not sure if this is the best answer but this could be achieved by doing something like:

computed: {
  compClass () {
    return 'class' in this.$vnode.data ? '' : 'default-class'
  },
}

You can check to see if a class was passed, if it was then have this return nothing as the class has already been added, otherwise add your default class.

Upvotes: 3

Related Questions