【问题标题】:Using custom elements in the content element with polymer在内容元素中使用自定义元素和聚合物
【发布时间】:2014-07-15 21:04:56
【问题描述】:

我正在尝试了解聚合物和影子 dom。处理动态内容时是否可以在自定义元素中使用自定义元素?例如,在 WordPress 中,我可以使用 <?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?> 列出我的菜单链接。如果我为我的菜单创建一个<main-menu> 元素,我将如何在每个<li> 周围包装另一个自定义元素?

这是我的主菜单 html 文件:

<link rel="import" href="/components/polymer/polymer.html">
<link rel="import" href="/components/core-header-panel/core-header-panel.html">
<link rel="import" href="/components/core-toolbar/core-toolbar.html">
<link rel="import" href="/components/paper-tabs/paper-tabs.html">

<polymer-element name="main-menu">
<template>
<style>

.main-menu ::content ul li {
  float: left;
  list-style-type: none;
  margin-left: 20px;
}

core-header-panel {
  height: 100%;
  overflow: auto;
  -webkit-overflow-scrolling: touch; 
}
core-toolbar {
  background: #03a9f4;
}

core-toolbar ::content ul li a {
  color: white;
  text-decoration: none;
  font-size: 14px;
  text-transform: uppercase;
}

</style>

<core-header-panel>
  <core-toolbar>
    <div class="main-menu">
      <paper-tabs>
        <content select="li"><paper-tab></paper-tab></content>
      </paper-tabs>
    </div>
  </core-toolbar>
</core-header-panel>

</template>
<script>
Polymer({});
</script>
</polymer-element>

显然,使用&lt;content select="li"&gt;&lt;paper-tab&gt;&lt;/paper-tab&gt;&lt;/content&gt; 并不能完成我想做的事情,但我不确定如何将&lt;paper-tab&gt; 包裹在每个&lt;li&gt; 周围

【问题讨论】:

    标签: polymer web-component shadow-dom


    【解决方案1】:

    在这种情况下,您需要使用getDistributedNodes 方法来获取所有这些lis,将它们转换为数组,然后将其交给重复模板。这个线程有更多解释:Element transclusion

    这是一个示例 (http://jsbin.com/hazay/9/edit):

    <polymer-element name="main-menu">
      <template>
        <style>
          :host {
            display: block;
          }
          ::content > * {
            display: none;
          }
        </style>
        <content id="c" select="li"></content>
        <paper-tabs>
          <template repeat="{{item in items}}">
            <paper-tab>{{item.textContent}}</paper-tab>
          </template>
        </paper-tabs>
      </template>
      <script>
        Polymer({
          items: [],
          domReady: function() {
            // .array() is a method added by Polymer to quickly convert
            // a NodeList to an Array
            this.items = this.$.c.getDistributedNodes().array();
          }
        });
      </script>
    </polymer-element>
    
    <main-menu>
      <li><a href="#">Foo</a></li>
      <li><a href="#">Bar</a></li>
      <li><a href="#">Baz</a></li>
    </main-menu>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      相关资源
      最近更新 更多