How to pass a component to a component in Polymer

2019-09-05 15:59发布

Suppose a component is composed of 3 internal components, where <outer-tag>'s shadow DOM looks something like this:

<div>
    <h1>The Outer Tag</h1>
    <my-tag1/>
    <my-tag2/>
    <my-tag3/>
</div>

Now let's say that <outer-tag>, <my-tag1/> and <my-tag3/> were always the same. But I want <my-tag2> to be pluggable. i.e. passed in. How would I do that in Polymer?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-09-05 16:15

If I understood the question right, you are looking for a way to distribute random children into the outer-tag's DOM (Documentation).

Here's how you would do it in your example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Outer-inner tags</title>
    <base href="https://polygit.org/components/">
    <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
    <link href="polymer/polymer.html" rel="import">
</head>
<body>

<dom-module id="outer-tag">
    <template>
        <div>
            <h1>The Outer Tag</h1>
            <my-tag1></my-tag1>

            <!-- Tell the <outer-tag> that something will go in here -->
            <content select=".tag2"></content>

            <my-tag3></my-tag3>
        </div>

    </template>
    <script>
        Polymer({
            is: 'outer-tag'
        });
    </script>
</dom-module>
<dom-module id="random-tag">
    <template>
        <div>
            <h2>Random Tag</h2>
            <div>I'm a random component</div>
        </div>
    </template>
    <script>
        Polymer({
            is: 'random-tag'
        });
    </script>
</dom-module>

<!-- Here's how to put them together -->
<outer-tag>
    <random-tag class="tag2"></random-tag>
</outer-tag>


</body>
</html>

Instead of ".tag2" you could more generally write "random-tag". The select attribute accepts CSS-like selectors.

查看更多
登录 后发表回答