David Vasquez
David Vasquez

Reputation: 1223

Vue.js - apply a class by default unless a class is manually added?

I'm just starting out in Vue.js and I'm a bit stuck figuring out if this is possible. Given the following component:

<button class="button large primary-gradient">{{ text }}</button>

If possible, I would like the classes "large primary-gradient" to be conditional based on if the developer adds other classes to the button component in the HTML later.

For example, if the developer writes

<custom-button text="hi"></custom-button>

it should render out

<button class="button large primary-gradient">hi</button>

However, if the developer writes:

<custom-button class="medium secondary" text="hi"></custom-button>

it should render out

<button class="button medium secondary">hi</button>

Essentially I'm attempting to create default class values for this button component that are only used if the developer doesn't add his own values. It seems to me this should be pretty easy to do, but my limited knowledge of Vue is hindering me a bit. Thanks for any insight!

Upvotes: 2

Views: 634

Answers (1)

Jacob
Jacob

Reputation: 78850

It's probably best to use props to control this:

Vue.component('custom-button', {
  props: {
    text: String,
    size: { type: String, default: 'large' },
    type: { type: String, default: 'primary-gradient' }
  },
  computed: {
    classes: function () {
      return ['button', this.size, this.type].join(' ')
    }
  },
  template: '<button v-bind:class="classes">{{ text }}</button>'
})

Usage:

<custom-button size="medium" type="secondary" text="Hi"/>

Upvotes: 3

Related Questions