我正在创造一个聚合物元素,使用铁-阿贾克斯。这将击中一个公共API来获取一个随机的fox imageUrl,并在DOM中显示。
需求
在单击button
时,我想对api进行新的调用,这将给我新的url。目前我正在使用<button type="button" onClick="window.location.reload();">
。但这会刷新页面。
问题
我浏览了这个StackOverflow solution并将其更改为version-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);
但是我得到了以下错误。侦听器方法未定义
问题
如何手动触发iron-ajax
按钮点击,这样我就可以得到新的response or imageUrl
和页面没有刷新?
发布于 2018-08-28 03:22:31
您的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);
https://stackoverflow.com/questions/52052416
复制