简体   繁体   中英

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!

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"/>

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