简介
ember-computed-style 是一个 Ember.js 框架下的 npm 包,用于在 Ember 组件中动态计算样式(CSS)属性。通过使用这个包,我们可以在不污染组件 HTML 的情况下改变组件的样式。
安装
使用命令 npm install ember-computed-style
即可安装。
使用
导入
在组件中导入 ember-computed-style
import computedStyle from 'ember-computed-style';
使用
在组件中定义计算属性 style
,该属性通过调用 computedStyle
方法来计算样式。
style: computed(function() { return computedStyle(this.getProperties('color', 'backgroundColor')); })
在组件的模板中,直接使用 style
属性来设置组件的样式。
<div {{bind-attr style=style}}></div>
示例
在下面的示例中,我们将通过系统计算属性 isDisabled
来动态改变按钮的样式。
-- -------------------- ---- ------- ------ ----- ---- -------- ------ ------------- ---- ----------------------- ------ ------- ------------------------ ----------- ----- ------ ------------------- - ----- ----- - --- --------------------- - ---------------------- - ------ - ------- ----------- - ---------------------- - ------- - -------- ------ --------------------- -- ---
<button {{bind-attr style=style}} {{bind-attr disabled=isDisabled}}> {{#if isDisabled}} Loading... {{else}} Click me! {{/if}} </button>
深入
在计算样式时,我们可以使用元组数组来定义属性和值的组合。
style: computed(function() { const style = {}; style.borderWidth = [this.get('borderWidth'), 'px']; style.borderStyle = this.get('borderStyle'); return computedStyle(style); })
上述代码将根据组件的 borderWidth
和 borderStyle
属性计算出 borderWidth
和 borderStyle
样式属性。而由于 borderWidth
属性是数值型,所以我们需要在计算时将其转换为带单位的字符串类型。
在样式的计算中,我们还可以借助计算属性定义样式属性。
-- -------------------- ---- ------- ------------ -- ----------------- ----------------------- ---------- - ------ ----------------------------- ----- ------- --- ------ ------------------- - ----- ----- - --- ----------------- - ----------------------------- ------ --------------------- --
上述代码将根据 borderWidth
和 borderStyle
属性计算出边框样式(border
)属性。
总结
通过 ember-computed-style 的使用,我们可以更加方便地动态计算组件的样式。同时,这也是 Ember.js 作为一个 UI 框架的特点之一。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/ember-computed-style