我正在创建自定义web组件"upload-widget",并在构造函数中声明三个常量,以便稍后在函数中引用:
const template = document.createElement('template');
template.innerHTML = `
<div id="dropper-zone">
<input type="file" name="file_input" id="file_name">
<button type="button" id="upload_btn">Upload</button>
<div id="upload_status"></div>
</div>
`;
class UploadWidget extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
const FILE_NAME = this.shadowRoot.getElementById("file_name");
const UPLOAD_BUTTON = this.shadowRoot.getElementById("upload_btn");
const UPLOAD_STATUS = this.shadowRoot.getElementById("upload_status");
};
upload_action() {
if (!FILE_NAME.value) {
console.log("File does not exists");
return;
UPLOAD_STATUS.innerHTML = 'File Uploaded';
};
connectedCallback() {
UPLOAD_BUTTON.addEventListener("click", () => this.upload_action());
}
}
customElements.define('upload-widget', UploadWidget);
这段代码失败了,因为Javascript不能识别"connectedCallback()"在函数&;upload_action()&;中也没有。将声明移动到任意一个函数中,使得常量仅在函数范围内有效,而不在函数范围之外。我如何声明常量/变量有效的类包括函数的整个范围?
您需要将它们声明为类变量,因此您的constructor
看起来像:
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
this.FILE_NAME = this.shadowRoot.getElementById("file_name");
this.UPLOAD_BUTTON = this.shadowRoot.getElementById("upload_btn");
this.UPLOAD_STATUS = this.shadowRoot.getElementById("upload_status");
};
在后面的代码中,您可以作为this.UPLOAD_BUTTON
访问它们。
建议:尝试使用camelCase命名变量,它看起来更"javascript"。所以把this.UPLOAD_BUTTON
写成this.uploadButton
注意你的模板使用有点臃肿,你可以这样做:
constructor() {
let html = `
<div id="dropper-zone">
<input type="file" name="file_input" id="file_name">
<button type="button" id="upload_btn">Upload</button>
<div id="upload_status"></div>
</div>`;
super() // sets AND returns this scope
.attachShadow({mode: 'open'}) // sets AND returns this.shadowRoot
.innerHTML = html;
}