1

我正在创建一个使用 Iron-ajax 的聚合物元素。这将访问公共 API 以获取随机狐狸 imageUrl 并在 DOM 中显示。

要求

单击button时,我想对 api 进行新的调用,这会给我新的 url。目前我正在使用<button type="button" onClick="window.location.reload();">. 但这会刷新页面。

问题

我浏览了这个StackOverflow 解决方案并将其更改为版本 3 解决方案。

class MyFox extends PolymerElement {
  static get template() {
    return html`
      <dom-bind>
      <template id="temp"> 
          <iron-ajax
            auto
            id="dataAjax"
            url=""
            handle-as="json"
            on-response="handleResponse"
            id="apricot">
          </iron-ajax>

          <button type="button" onClick="window.location.reload();">Next Image</button>
          <br> <br>
          <img src="[[imgUrl]]" width="300">
      </template>
      </dom-bind>
    `;
  }
  static get properties() {
    return {
      prop1: {
        type: String,
        value: 'my-fox',
      },
      imgUrl: {
        type: String,
      }
    };
  }
  handleResponse(event, res) {
    this.imgUrl = res.response.image; 
  }
  nextImg() {
    // new call to iron-ajax for new image
    var temp = document.querySelector('#temp');
    temp.$.dataAjax.generateRequest();
  }
}

window.customElements.define('my-fox', MyFox);

但我收到以下错误。 未定义侦听器方法handleResponse

狐狸错误

问题

如何iron-ajax在按钮单击时手动触发,这样我就可以获得新response or imageUrl的并且页面不刷新?

4

1 回答 1

1

您的 Web 组件中有几个错误

class MyFox extends PolymerElement {
  static get template() {
    return html`
          <iron-ajax
            auto
            id="dataAjax"
            url=""
            handle-as="json"
            on-response="handleResponse">
          </iron-ajax>

          <button type="button" on-tap="nextImg">Next Image</button>
          <br> <br>
          <img src="[[imgUrl]]" width="300">
    `;
  }
  static get properties() {
    return {
      prop1: {
        type: String,
        value: 'my-fox',
      },
      imgUrl: {
        type: String,
      }
    };
  }
  handleResponse(event, res) {
    this.imgUrl = res.response.image; 
  }
  nextImg() {
    // new call to iron-ajax for new image
    this.$.dataAjax.generateRequest();
  }
}

window.customElements.define('my-fox', MyFox);
于 2018-08-28T11:22:31.303 回答