1 回答
TA贡献1865条经验 获得超7个赞
那是因为this分配给window.onfocus等的函数中的 不是指 VueJS 应用程序本身,而是指window对象。如果将其转换为箭头函数,它应该可以工作:
methods:{
detectFocusOut() {
console.log("It is here");
var inView = false;
window.onfocus = window.onblur = window.onpageshow = window.onpagehide = (e) => {
if ({ focus: 1, pageshow: 1 }[e.type]) {
if (inView) return;
this.tabFocus = true;
inView = true;
} else if (inView) {
this.tabFocus = !this.tabFocus;
inView = false;
}
};
},
}
就个人而言,我建议不要使用菊花链分配。您可以简单地将所有这些逻辑抽象为一个函数:
methods:{
detectFocusOut() {
let inView = false;
const onWindowFocusChange = (e) => {
if ({ focus: 1, pageshow: 1 }[e.type]) {
if (inView) return;
this.tabFocus = true;
inView = true;
} else if (inView) {
this.tabFocus = !this.tabFocus;
inView = false;
}
};
window.addEventListener('focus', onWindowFocusChange);
window.addEventListener('blur', onWindowFocusChange);
window.addEventListener('pageshow', onWindowFocusChange);
window.addEventListener('pagehide', onWindowFocusChange);
}
}
添加回答
举报