我让 Nuxt JS 2.9.x 在通用模式下运行,每个页面都加载了一个组件。我使用了两个事件监听器:blur
和 focus
,它们应该分别运行。 blur
事件监听器应该只在切换浏览器选项卡时运行,但似乎在页面加载时运行...我该如何更改它?我的组件 JS:
export default {
mounted () {
document.addEventListener('blur', this.blurTitle(false));
document.addEventListener('focus', this.blurTitle(true));
},
methods: {
blurTitle(location) {
const currentPageTitle = document.title
if (location) {
document.title = currentPageTitle
} else {
document.title = 'Please come back...'
}
}
}
}
我试图在离开页面时显示一些不同的文本,但在返回时显示原始页面标题。该网站将被编译成静态生成的网站。
最佳答案
您正在立即调用 blurTitle
。这:
document.addEventListener('blur', this.blurTitle(false));
等同于:
const fn = this.blurTitle(false)
document.addEventListener('blur', fn);
我怀疑你想要的是这样的:
document.addEventListener('blur', this.blurTitle.bind(this, false));
这从 this.blurTitle
创建了一个新函数,第一个参数绑定(bind)到 false
。
或者如果你更喜欢箭头函数:
document.addEventListener('blur', () => this.blurTitle(false));
这将创建一个将调用 blurTitle
并传递 false
的包装函数。
关于javascript - Nuxt JS 事件监听器触发两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58344302/