我对 lit-element 比较陌生,我尝试创建一个具有复选框的元素,理想情况下应该根据对 ajax 调用的响应进行检查。我运行我的代码时,无论 ajax 响应如何,都始终选中该复选框。我也收到此错误
Uncaught TypeError: Cannot read property 'shadowRoot' of undefined
at HTMLElement.<anonymous> (fhir-active-status.js:57)
at HTMLElement.fire (legacy-element-mixin.js:630)
at HTMLElement._handleResponse (iron-ajax.js:551)
我认为这是一个生命周期问题,但我无法弄清楚。我究竟做错了什么?
import {LitElement, html} from 'lit-element';
import '@material/mwc-formfield/mwc-formfield.js';
import '@material/mwc-checkbox/mwc-checkbox.js'
import '@polymer/iron-ajax/iron-ajax.js';
class FhirActiveStatus extends LitElement {
static get properties() {
return {
/**activeStatus is used to show active status of person true or false. Use this property to show/hide. Default: true */
activeStatus: {type:String},
/**url is used to make AJAX call to FHIR resource. Default: null */
url: {type:String},
/**value is used to take the input value of each field*/
value: {type:Boolean},
}
}
/**default value of properties set in constructor*/
constructor() {
super();
this.activeStatus = 'true';
this.value = false;
this.url = "";
}
async updated() {
this.shadowRoot.getElementById('ajax').addEventListener('iron-ajax-response', function (e) {
var active = this.parentNode.host;
if (e.detail.response.active) {
active.shadowRoot.querySelector('.activeState').checked = true;
}
else if (!e.detail.response.active) {
active.shadowRoot.querySelector('.activeState').checked = false;
}
else {
this.parentNode.removeChild(this.parentNode.querySelector('#activeDiv'));
}
});
}
render() {
return html`
<div id="activeDiv">
${this.activeStatus !== 'false' ? html`<mwc-formfield class="activeStatus" alignEnd label="ACTIVE STATUS:">
<mwc-checkbox id="active" checked="${this.value}" class="activeState" on-click="${e => this.value = e.target.value}"></mwc-checkbox>
</mwc-formfield>` : ''}
<iron-ajax id="ajax" bubbles auto handle-as="json" url="${this.url}"></iron-ajax>
</div>
`;
}
}
window.customElements.define('fhir-active-status', FhirActiveStatus);