使用聚合物如何将类绑定到宿主元素



我知道你可以使用下面的自定义元素中的元素语法将元素的属性绑定到class属性,

<div id="arrow" class$="{{propertyName}}"></div>

但是是否可以将绑定应用到宿主元素本身?我已经尝试了如下所示,以及其他各种尝试,但都失败了!

<link rel="import" href="../bower_components/polymer/polymer.html">
<dom-module id="my-element" class$="{{propertyName}}">
    <template>
        <style>
        </style>
    </template>
    <script>
        Polymer({
            is:'my-element'
        });
    </script>
</dom-module>

你想做的是可能的,通过反映属性值的属性。

Polymer({
  properties: {
    someProp: {
      reflectToAttribute: true
    }
  }
});

请参见下面在主机节点上如何设置classother属性的值。

我不确定,虽然重新定义内置属性,如class是明智的。如果您想使用反射属性进行样式化,最好使用属性选择器,就像我对me-elem[other]所做的那样。

Polymer({
  is: 'my-elem',
  properties: {
    class: {
      reflectToAttribute: true,
      value: 'red'
    },
    other: {
      type: Boolean,
      reflectToAttribute: true,
      value: true
    }
  }
});
<!DOCTYPE html>
<html>
<head>
  <base href="https://polygit.org/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link href="polymer/polymer.html" rel="import"/>
</head>
<body>
  <style>
    .red {
      color: red;
    }
    
    my-elem[other] {
      border: solid 1px black;
    }
  </style>
  
  <my-elem></my-elem>
  
  <dom-module id="my-elem">
    <template>
      Some text   
    </template>
  </dom-module>
</body>
</html>

最后,要小心reflectToAttribute,因为在DOM中序列化大值时,您可能会看到性能下降。

最新更新