首页 > 解决方案 > Nuxt JS 事件监听器触发两次

问题描述

我有 Nuxt JS 2.9.x 在通用模式下运行,每个页面都加载了一个组件。我正在使用两个事件侦听器:blurfocus,它们都应该单独运行。事件侦听器应仅在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...'
      }
    }

  }
}

我试图在离开页面时显示一些不同的文本,但是在返回时,显示原始页面标题。该站点将被编译成静态生成的站点。

标签: javascriptvue.jsvuejs2nuxt.js

解决方案


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.


推荐阅读