Polymer 2.0 如何扩展 PolymerElements app-layout 和 app-drawer

Polymer 2.0 How to extend PolymerElements app-layout and app-drawer

我是 Polymer 2.0 的新手,我正在尝试创建自定义元素。

我能够扩展我自己的自定义元素并且它工作正常。我只是想看看我是否可以扩展 PolymerElements app-layout 的 app-drawer 元素 https://www.webcomponents.org/element/PolymerElements/app-layout

我试过了,但没用。

<link rel="import" href="/bower_components/app-layout/app-layout.html">

class MyElement extends AppLayout {
  static get is() { return 'my-element'; }
};

customElements.define(MyElement.is, MyElement);

它给我一个错误 Uncaught ReferenceError: AppLayout is not defined。即使我试图确保应用程序布局具有正确的导入脚本,我也可以使用应用程序布局元素,如应用程序抽屉。

是AppLayout这个名字写错了吗?我尝试了不同的名称,例如 Polymer.Applayout 等,但仍然出现相同的错误。我尝试扩展我自己的自定义元素,该元素位于同一个 bower_components 文件夹中,并且可以正常工作。

class ExtendedElement extends MyElement {
  static get is() { return 'extended-element'; }
};

有什么建议吗?谢谢!

我设法找到有用的东西here and here

此示例将扩展 <app-layout>

<app-drawer> 元素
<dom-module id="my-sub-element">
  <template id="styles">
    <style>
      div {
        background-color: gray;
      }
    </style>
  </template>

  <script>

  (function() {
    let subTemplate;

    class MySubElement extends customElements.get('app-drawer') {
      /**
       * This will return our template inherited from superclass <app-drawer> with our styles inserted
       */
      static get template() {
        if (!subTemplate) {
          // first clone our superclass <app-drawer> template
          let superClass = customElements.get('app-drawer');
          subTemplate = superClass.template.cloneNode(true);

          // here we will get the content of our <style> so we can insert them into the superclass <style>
          // note the added id="styles" in our template tag above
          const subStyle = Polymer.DomModule.import('my-sub-element', 'template#styles').content;

          // get the content of current style from superClass
        const superStyle = subTemplate.content.querySelector('style');

          // append our added style at the bottom of the current style to get higher priority
          superStyle.parentNode.appendChild(subStyle);
        }
        return subTemplate;
      }

    }

    customElements.define('my-sub-element', MySubElement);

  })();

  </script>
</dom-module>

希望对您有所帮助。目前这对我有用。我通读了这个讨论 here 以更清楚地了解扩展 .如果有更好的方法,请 add/edit 我的回答。干杯!