我刚刚开始使用 Vue.js,我有点不知道这是否可行。给定以下组件:
<button class="button large primary-gradient">{{ text }}</button>
如果可能的话,我希望“large Primary-gradient”类能够以开发人员稍后是否向 HTML 中的按钮组件添加其他类为条件。
例如,如果开发人员编写
<custom-button text="hi"></custom-button>
它应该渲染出来
<button class="button large primary-gradient">hi</button>
但是,如果开发人员写道:
<custom-button class="medium secondary" text="hi"></custom-button>
它应该渲染出来
<button class="button medium secondary">hi</button>
本质上,我正在尝试为此按钮组件创建默认类值,这些值仅在开发人员不添加自己的值时使用。在我看来,这应该很容易做到,但我对 Vue 的有限了解有点阻碍了我。感谢您的任何见解!
最佳答案
最好使用 props 来控制它:
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>'
})
用法:
<custom-button size="medium" type="secondary" text="Hi"/>
关于javascript - Vue.js - 默认应用一个类,除非手动添加一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41497189/