Ember 1.13,在组件中按顺序排列类名

Ember 1.13, class names order in a component

本文关键字:顺序 排列 组件 Ember      更新时间:2023-09-26

我创建了一个简单的组件来从SVG精灵中呈现图标。这个组件应该有一个默认的CSS类来全局管理它的样式(.svg-icon)。此外,我希望有可能通过'class'属性通过类名添加一些依赖于上下文的样式。

JS:

App.SvgIconComponent = Ember.Component.extend
   layoutName: 'components/svg-icon'
   classNames: ['svg-icon']
   tagName: 'svg'
   attributeBindings: ['width', 'height', 'fill'],
   width: 16
   height: 16
   fill: 'currentColor'

模板:

<use xlink:href="#svg-icon-{{name}}"/>

用法:

{{svg-icon name="facebook" class="social__icon" width="14" height="14"}}
HTML输出:

<svg id="ember1012" width="14" height="14" fill="currentColor" class="social__icon ember-view svg-icon">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#svg-icon-facebook"></use>
</svg>

问题是Ember将我的默认类(.svg-icon)推到了类列表的末尾。但是,为了避免级联的一些问题,我需要在类列表的开头放置这个类(class="svg-icon social__icon ember-view")。有可能实现吗?

我知道,我可以用classNameBindings属性设置类名,但在这种情况下,我需要使用一些不同于'class'的属性。最好使用原生的'class'属性。

非常感谢。

试试这个,

{{svg-icon name="facebook" classNames="social__icon" width="14" height="14"}}

以上将工作,但它不使用类属性。所以它不符合你的要求。

但如果不符合您的要求,您可以尝试在init方法中手动设置classNames。

init(){
    this._super(...arguments);
    console.log(' Classess ',this.get('classNames')); //You will get classNames, you can do rearrange the classNames array
    this.get('classNames').unshiftObject('svg-icon'); //to force svg-icon to be first in classNames array.    
  }

Update1

上面的

init()不起作用。所以我认为classNames值是最后添加的。首先使用本地class是不可能的。但是对于你的要求

我知道,我可以设置类名与classNameBindings属性,但在这种情况下,我将需要使用一些属性不同于'class'

您可以为特定属性指定不同的类名。

{{my-component is_social__icon=false }}

my-component.js内部

classNameBindings:['is_social__icon:social__icon']

更新2
1)你也可以在classNameBindings

中为true和false值指定类名
export default Ember.Component.extend({
  classNameBindings: ['isEnabled:enabled:disabled'],
  isEnabled: false
});

isEnabled - true -那么它将包含enabled类名isEnabled - false -那么它将包含disabled类名

2)你甚至可以指定只在false值时添加的类名。

 classNameBindings: ['isEnabled::disabled'],
3)你可以指定多个属性
 classNameBindings:['isSocialIcon':'social__icon','isActive':'selected']

可以为组件提供isSocialIconisActive属性的值。

{{my-component isSocialIcon=true isActive=(unless social.inactive) }}

如果isActive被解析为true,那么它将添加social__icon selected类到my-component。

参考:https://guides.emberjs.com/v1.13.0/components/customizing-a-components-element/#toc_customizing-class-names