简体   繁体   English

Vue.js-默认情况下应用类,除非手动添加了类?

[英]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. 我刚开始使用Vue.js,但我想弄清楚这是否可行。 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. 如果可能的话,我希望基于开发人员是否稍后将其他类添加到HTML中的按钮组件的情况下,将“大型主要渐变”类作为条件。

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. 在我看来,这应该很容易做到,但是我对Vue的有限了解在某种程度上阻碍了我。 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"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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