javascript - Nuxt JS 事件监听器触发两次
问题描述
我有 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
,第一个参数绑定到false
。
或者,如果您更喜欢箭头功能:
document.addEventListener('blur', () => this.blurTitle(false));
这将创建一个包装函数,该函数将调用blurTitle
、传递false
.
推荐阅读
- angular - Primeng - 如何在多选/下拉列表的标题中添加一个按钮?
- vb.net - 想要将文本框中的行添加到列表框中,如果它包含单词中的单词
- powershell - 在 PowerShell 中管理基于批处理的服务器
- dockerfile - ECS Fargate 日志文件位置
- python - StreamHandler 的实例默认使用 sys.stderr 是什么意思?
- r - 更改数据框格式并使用复制作为列执行方差分析
- vba - 使用 VBA 处理在 VSTO 加载项中定义的功能区控件
- python-3.x - AdamOptimizer 返回无效数据类型错误
- javascript - “vue.config.js”文件在哪里?
- json - 在 Unity 3D 中使用从 WWW 接收的数据