Beu*_*biu 2 javascript vue.js vuejs2
我在这里找到了一个很好的例子,看起来很适合我的需要,我尝试在我的Vuejs应用程序中实现它。,但到目前为止,该代码没有检测到任何更改,也没有错误。
data() {
return {
tabFocus:false,
}
}
created() {
this.detectFocusOut();
},
watch:{
tabFocus(value) {
console.log("New value:", value);
},
}
methods:{
detectFocusOut() {
console.log("It is here");
var inView = false;
window.onfocus = window.onblur = window.onpageshow = window.onpagehide = function(
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;
}
};
},
}
Run Code Online (Sandbox Code Playgroud)
这是因为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;
}
};
},
}
Run Code Online (Sandbox Code Playgroud)
就我个人而言,我建议不要进行菊花链分配。您可以简单地将所有逻辑抽象为一个函数:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2522 次 |
| 最近记录: |