簡體   English   中英

如何獲取dom-if或dom-repeat中的元素?

[英]How to get element in dom-if or dom-repeat?

<dom-module id="weather-data">
<template>
  <style is="custom-style" include="iron-flex iron-flex-alignment">


 :host {
      display: block;
      font-family: Roboto;
    }

    paper-progress {
      top: 0;
      left: 0;
      position: fixed;
      width: 100%;
      --paper-progress-active-color: var(--paper-light-blue-500);
      --paper-progress-secondary-color: var(--paper-light-blue-100);
    }

    paper-icon-button {
      margin: 0 auto;
      margin-top: 20px;
      display: block;
    }

    #weatherIcon {
      width: 200px;
      height: 200px;
    }

    table {
      border-collapse: collapse;
    }

    table td {
      text-align: center;
      border: 1px solid #006064;
      padding: 5px;
    }

  </style>

  <paper-progress
    id="request-progress"
    indeterminate
    hidden$="[[!activeRequest]]">
  </paper-progress>

  <iron-ajax
    id="getData"
    auto
    url="[[weatherApiUrl]]"
    handle-as="json"
    last-response="{{weatherResponse}}"
    last-error="{{error}}"
    params="[[_getGegevensVanLocatie(coordinaten.latitude,        coordinaten.longitude)]]"
    loading="{{activeRequest}}">
  </iron-ajax>

  <template is="dom-if" id="tmp" if="[[weatherResponse]]">
    <paper-icon-button
    id="location-button"
    disabled$="{{disableLocationButton}}"
    on-tap="_getLocation"
    icon="maps:my-location"
    alt="Zoek mijn huidige locatie">
    </paper-icon-button>

    <div>
      <div class="horizontal center-justified layout">
        <h2>Weer voor locatie: <span>[[_maakLocationString(weatherResponse.query.results.channel.location)]]</span></h2>
      </div>
      <div class="horizontal center-justified layout">

        <iron-icon
          id="weatherIcon"
          icon="[[_getIcon(weatherResponse.query.results.channel.item.condition.code)]]">
        </iron-icon>

      </div>
      <div class="horizontal center-justified layout">
        <h2>
          <span>
            [[weatherResponse.query.results.channel.item.condition.text]],
            [[weatherResponse.query.results.channel.item.condition.temp]]° [[weatherResponse.query.results.channel.units.temperature]]
          </span>
        </h2>
      </div>
      <div class="horizontal center-justified layout">
        <table>
          <tr>
            <td>
              <iron-icon icon="icons:arrow-upward"></iron-icon>
            </td>
            <td>
              <iron-icon icon="icons:arrow-downward"></iron-icon>
            </td>
          </tr>
          <tr>
            <td>[[weatherResponse.query.results.channel.astronomy.sunrise]]</td>
            <td>[[weatherResponse.query.results.channel.astronomy.sunset]]</td>
          </tr>
        </table>
      </div>
      <div class="horizontal center-justified layout">
        <h5 id="update-time">
          Gegevens geraadpleegd om: [[weatherResponse.query.results.channel.item.condition.date]]<span></span>
        </h5>
      </div>
    </div>
  </template>
</template>

<script>


    Polymer({
        is: 'weather-data',
        properties: {
            weatherApiUrl: {
                type: String,
                value: "https://query.yahooapis.com/v1/public/yql"
            },
            coordinaten: {
                type: Array,
                value: {
                    longitude: 22,
                    latitude: 22
                }
            }
        },
        ready: function() {
            if (navigator.permissions && navigator.permissions.query) {
                navigator.permissions.query({
                    name: 'geolocation'
                }).then(function(status) {
                    if (status.state === 'granted') {
                        console.log("Permisson already granted");
                        _getLocation();
                    } else {
                        console.log("Location not YET granted, using default coordinates");
                        if (status.state === "denied") {
                            console.log("Denied");
                        }
                    }
                });
            } else {
                console.log("Permission not available");
                console.log("Using standard coordinates");
            }
        },
        _getLocation: function() {
            console.log("Getting location");
        },
        _getGegevensVanLocatie: function(latitude, longitude) {
            var latLong = '(' + 51.0339 + ',' + 3.7094 + ')';
            return {
                format: 'json',
                q: 'select * from weather.forecast where woeid in ' +
                    '(select woeid from geo.places(1) where text="' + latLong + '") and u="c"'
            };
        },
        _maakLocationString: function(location) {
            if (location.city && location.region) {
                return location.city + ', ' + location.region;
            } else {
                return location.city || 'Onbekend';
            }
        },
        _getIcon: function(code) {
            if (code >= 37 || code <= 12) {
                return "image:flash-on";
            }

            if (code <= 18) {
                return "image:flare";
            }

            if (code <= 30) {
                return "image:wb-cloudy";
            }

            return "image:wb-sunny";
        }
    })
</script>

這就是我的代碼。 我想做的是,當狀態更改為“已授予”時,在導航器上授予了權限時,獲取了<paper-icon-button>元素。 但是,這不適用於this.$.location-buttonthis.$$('#location-button)

這是因為我在ready()函數中使用了它嗎?

用於自動節點查找的Polymer文檔狀態:

注意:使用數據綁定動態創建的節點(包括dom-repeatdom-if模板中的節點)不會添加到this.$哈希中。 哈希僅包含靜態創建的本地DOM節點(即,元素最外層模板中定義的節點)。

因此,在您的情況下,您必須使用this.$$('#location-button')來查詢按鈕,而不是使用this.$['location-button']

我假設在查詢#location-button ,布爾型weatherResponsefalse ,在這種情況下,該按鈕在DOM中將不存在。 如果在ready()中將Boolean設置為true ,則在查詢按鈕之前,必須等待按鈕在下一個渲染(使用Polymer.RenderStatus.afterNextRender() )中被標記:

ready: function() {
  this.weatherResponse = true;
  Polymer.RenderStatus.afterNextRender(this, () => {
    console.log(this.$$('#location-button'));
  });
}

codepen

dom-if模板僅在其if屬性變為true時才將其內容標記到DOM中。 標記內容后, if屬性更改,它只會隱藏並顯示內容。 盡管將restamp設置為true會破壞並重新創建內容。

因此,在獲取weatherResponse在元素ready生命周期回調中尚未完成)之前,您無法找到paper-icon-button

請注意,在有關聚合物條件模板用法的文檔中,它說:

由於通常隱藏和顯示元素比破壞並重新創建它們要快得多,因此條件模板僅在被壓印的元素相對較重且在給定用法中很少(或永遠不會)滿足條件時才可節省初始創建成本。 。 否則,自由使用條件模板實際上會增加大量的運行時性能開銷。

因此,在您的情況下,也許將dom-if模板更改為具有hidden$="[[!weatherResponse]]"屬性的元素(例如div )。 當調用ready時,也將在paper-icon-button上蓋章。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM