获取铁页中的页数

时间:2017-11-29 13:28:14

标签: polymer-2.x iron-pages

我想显示当前所选页面的编号和铁页中所有页面的编号(例如“第1页,共100页”)。

获取前者非常简单,因为您可以查找selected-changed事件。对于后者我不知道如何得到它。我正在考虑在iron-pages中获取子元素的数量,但这似乎并不可靠。

1 个答案:

答案 0 :(得分:2)

您可以做的是确保每个页面都有相应的编号作为属性。您可以通过评估子元素来获取页面数(忽略后备页面)。

一个工作示例:

<!DOCTYPE html>
<html>

<head>
    <base href="//polygit.org/components/">
    <script src="webcomponentsjs/webcomponents-lite.js"></script>
    <link rel="import" href="polymer/polymer.html">

    <link rel="import" href="iron-pages/iron-pages.html">


    <dom-module id="example-component">
        <template>
            <style>
                :host {
                    display: block
                }
            </style>

            <input value="{{pageName::input}}" placeholder="Type a page name here.">

            <iron-pages id="ironPages" selected="[[pageName]]" attr-for-selected="page-number" fallback-selection="fallback">
                <div page-number="1">One</div>
                <div page-number="2">Two</div>
                <div page-number="3">Three</div>
                <div page-number="fallback">
                    Change pages by typing '1', '2', or '3' in the input above.
                </div>
            </iron-pages>

            <div id="pageNumbering">Page [[currentPage]] of [[totalPages]]</div>

        </template>

        <script>
            class ExampleComponent extends Polymer.Element {
                static get is() {
                    return 'example-component';
                }
                static get properties() {
                    return {
                        currentPage: {
                            type: Number,
                            value: 0,
                        },
                        totalPages: {
                            type: Number,
                            value: 0,
                        }
                    };
                }

                connectedCallback() {
                    super.connectedCallback();
                    // fallback doesn't count
                    this.totalPages = this.$.ironPages.children.length - 1;
                    this.addEventListener('iron-select', this._onPageChanged);
                }

                _onPageChanged() {
                    let currentPage = this.$.ironPages.selectedItem.getAttribute('page-number');

                    if (currentPage == "fallback") {
                        this.$.pageNumbering.hidden = true;
                    }

                    if (currentPage <= this.totalPages) {
                        currentPage = parseInt(currentPage);
                        this.set('currentPage', currentPage);
                        this.$.pageNumbering.hidden = false;
                    }
                }

            }

            customElements.define(ExampleComponent.is, ExampleComponent);
        </script>
    </dom-module>

</head>

<body>
    <example-component></example-component>
</body>

</html>