【问题标题】:Nuxt JS event listener fires twiceNuxt JS 事件监听器触发两次
【发布时间】:2019-10-11 15:23:42
【问题描述】:

我有 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...'
      }
    }

  }
}

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

【问题讨论】:

    标签: javascript vue.js vuejs2 nuxt.js


    【解决方案1】:

    您立即致电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

    【讨论】:

      猜你喜欢
      • 2015-11-22
      • 2017-01-08
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多