从一个web组件(一个子组件),我需要向父组件传递一个事件。因此,我使用dispatchEvent。它工作正常,在异步函数(firebase.auth()、.signOut()、.then())中使用时,返回以下错误:
未捕获的TypeError:无法读取未定义的属性“”dispatchEvent“”
代码如下:
import Template from "./template.js";
export class NavBar extends HTMLElement {
constructor() {
super();
this.attachShadow({mode:"open"})
.innerHTML = Template.render();
this.dom = Template.mapDOM(this.shadowRoot);
this.addEventListener("click", e => this.onClick(e));
}
onClick(e) {
e.preventDefault();
switch (e.composedPath()[0].id){
case "welcome":
const customElements = new CustomEvent("pageChange", {
bubbles: true,
composed: true,
detail: {
page: "welcome"
}
});
this.dispatchEvent(customElements); // works!
break;
case "login":
const customElements2 = new CustomEvent("pageChange", {
bubbles: true,
composed: true,
detail: { page: "login" }
});
this.dispatchEvent(customElements2); // works!
break;
case "logout":
firebase.auth().signOut()
.then(function(){
const customElements3 = new CustomEvent("pageChange", {
bubbles: true,
composed: true,
detail: { page: "welcome" }
});
this.dispatchEvent(customElements3); // doesn't work
});
break;
}
};
};
if (!customElements.get("my-navbar")){
customElements.define("my-navbar", NavBar)
}这就好像"this“不再是"shadowRoot”。有人知道我做错了什么吗?
谢谢您抽时间见我。
发布于 2020-06-28 18:48:57
尝试箭头函数,问题是您作为回调传递给then的回调函数定义了自己的this,因为它定义了一个新的作用域,然而,箭头函数允许您使用词法this,这意味着它将使用查找来查找this。因此,您的代码应如下所示
firebase.auth().signOut()
.then(() => { // this line
const customElements3 = new CustomEvent("pageChange", {
bubbles: true,
composed: true,
detail: { page: "welcome" }
});
this.dispatchEvent(customElements3); // should work
}); https://stackoverflow.com/questions/62621393
复制相似问题