我正在使用 Vue.js(尽管我的问题对任何框架都有效),您可以在其中传递一个简单的对象和 truthy
键作为类应用。
例如。 <div :class="{ 'class1': prop1, 'class2', prop2 }">Hello</div>
.如果prop1
是真的,class1
适用。如果两个 Prop 都为真,则 class1
和 class2
申请。
此外,我正在使用 Atomic/Utiliy 类。因此,其中没有具有多个属性的类,而是 color:red
我用 C(red)
, 对于 background-color:blue
我用 Bgc(blue)
等等……
以此为基础,我有一个具有以下 Prop 的按钮组件:
- 主题 - 具有主要值(value)、次要值(value)。
- 反转 - 真/假
- 禁用 - 真/值
为那么多相互关联的 Prop 创建一个类对象变得有点困惑:
{
'Bdc(color1) Bdc(color2):h Bdc(color3):a': this.theme === 'primary' && !this.linkOnly,
'Bdc(color4) Bdc(color5):h Bdc(color5):a': this.theme === 'positive' && !this.linkOnly,
'Bdc(color1) Bdc(color2):h Bdc(color4):a': this.theme === 'negative' && !this.linkOnly,
'Bdc(color3) Bdc(color3):h Bdc(color3):a': (this.theme === 'default' && !this.linkOnly) ||
(!this.theme && !this.linkOnly),
'C(color1) C(color2):h C(color3):a':
this.theme === 'primary' && (this.linkOnly || this.inverted),
'C(color3) C(color4):h C(color5):a':
this.theme === 'positive' && (this.linkOnly || this.inverted),
'C(color2) C(color3):h C(color4):a':
this.theme === 'negative' && (this.linkOnly || this.inverted),
'C(color5) C(color6):h C(color7):a':
(this.theme === 'default' && (this.linkOnly || this.inverted)) ||
(!this.theme && (this.linkOnly || this.inverted)),
'C(color1)': !(this.linkOnly || this.inverted)
如您所见,那里的条件很难阅读。并且添加一些新的 prop 会使正确实现变得更加困难。
还有一件更重要的事情:我正在使用的原子 CSS 库要求最终类出现在代码中,因为它解析并将它们放入 CSS 中。所以'Bgc(' + someVariable + ')'
不会工作,因为它不是我们想要的 final类。
我正在寻求有关如何重构这些条件以使样式易于使用原子/实用程序类进行管理的帮助。
最佳答案
您可以将所有逻辑移动到 computed
属性:
function getBtnClass () {
let classes = []
if (this.theme === 'primary') classes.push('Bdc(color1)', 'Bdc(color2):h')
...
return classes.join(' ')
}
并将其传递给模板:<div class='getBtnClass'>...</div>
关于css - 根据其 Prop 有条件地在组件上应用实用程序类的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52040101/