1

我正在通过 Polymer 2.0 使用 Web 组件。

我要编写的最终 HTML 如下所示:

<card size="small">
  <card-header>
    // Markup
  </card-header>
  <card-body>
    // Markup
  </card-body>
  <card-footer>
    // Markup
  </card-footer>
</card>

如您所见,我将 size 传递给顶级组件。我打算听听这些卡片的宽度,并减少页眉、正文和页脚的填充,当它们变得更小尺寸时,基本上是响应式元素。

我不知道该怎么做是获取 size 的属性值以传递给card-header,card-bodycard-footerpolymer 声明。

这是我的定义card

<link rel="import" href="card-header.html">
  <dom-module id="card">
      <template>
        <style>
          // Style things
        </style>

        <slot></slot>
      </template>
      <script>
    Polymer({
      is: 'card',

      properties: {
        size: {
          type: String,
          value: "medium",
          observer: '_observeSize'
        },
      },

      _observeSize: function () {
        const sizes = {
          tiny: "1em",
          small: "2em",
          medium: "3em",
          large: "6em"
        };

        if (this.size == "tiny") {
          this.customStyle['--padding-x'] = sizes.tiny;
          this.customStyle['--padding-y'] = sizes.tiny;
        } else if (this.size == "small") {
          this.customStyle['--padding-x'] = sizes.small;
          this.customStyle['--padding-y'] = sizes.small;
        } else if (this.size == "medium") {
          this.customStyle['--padding-x'] = sizes.medium;
          this.customStyle['--padding-y'] = sizes.medium;
        } else if (this.size == "large") {
          this.customStyle['--padding-x'] = sizes.large;
          this.customStyle['--padding-y'] = sizes.large;
        } else {
          this.customStyle['--padding-x'] = sizes.medium;
          this.customStyle['--padding-y'] = sizes.medium;
        }

        this.updateStyles();
      },

      _responsiveObserver: function () { 
        // Update this.size based on width of this element.
      }

    });
  </script>
</dom-module>

这就是我的定义card-header

<dom-module id="card-header">
  <template>
      <style>
        // Style
      </style>
    <slot></slot>

  </template>

  <script>
    Polymer({
      is: 'card-header',

      properties: {
        size: {
          type: String,
        }
      },

      ready: function () {
        console.log(this.size);
        // console.log(hostValue::size); ???? something like this ????
      }
    });
  </script>
</dom-module>

TL;DR:如何在不使用 Polymer 更新 DOM 中的属性的情况下获取父节点的属性值,或者将值传递给特定的子节点(card-headercard-body或)?card-footer

4

1 回答 1

1

解决方案

有几种方法可以解决这个问题,但我意识到我正在将我需要的内容放入 中<slot></slot>,因此我可以在卡片级别执行填充逻辑,然后在 CSS 变量中处理。

  _observeSize: function () {
    // const and if else blocks still exist, untouched. Since they set the customStyle object on this element...

    var children = this.querySelectorAll('card-header, card-body, card-footer');

    children.forEach(function (child) {
      child.style = this.customStyle;
    });

    this.updateStyles();
  },
于 2017-03-09T16:59:11.400 回答