javascript - Nuxt JS 事件监听器触发两次

标签 javascript vue.js vuejs2 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...'
      }
    }

  }
}

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

最佳答案

您正在立即调用 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/

相关文章:

javascript - Luxon:根据区域设置按工作日开始排序所有工作日

javascript - Vue.js:对子元素使用 CSS 类

vue.js - 更新的表单输入未发布新值

vue.js - Vuetify 嵌套表单元素不适用于 $refs

javascript - 如何使用javascript查找最大用户浏览器窗口宽度和当前

javascript - 在html5 canvas中显示和绘制

javascript - 你能安排事件回调的冒泡顺序吗?

javascript - 为什么 onclick 事件不适用于 vue-router?

vue.js - Vue.js 中所有导入的数组都必须是响应式的吗?

javascript - 使用 , 而不是按 enter 验证带有筹码的标签