【问题标题】:Error count up and down when catch event mouse wheel in vuejs在vuejs中捕获事件鼠标滚轮时错误计数
【发布时间】:2022-07-20 23:59:45
【问题描述】:

我有一个示例 .vue 文件,运行时发生错误 this.wheel_scale is not a function

<template>
   <div class="count-wheel">{{ scale }}</div>
   ...
   <div id="singapore-map"></div>
</template>

...
export default {
   data() {
      return {
         scale: 1
      }
   },
   mounted() {
      var sg = document.getElementById("singapore-map");
      sg.parentElement.addEventListener("wheel", function (e){
         this.wheel_scale(e, sg);
      });
   },
   methods: {
    wheel_scale: function (e, t) {
       e.wheelDelta < 0 ? this.scale-- : this.scale++;
    }
  },
}

【问题讨论】:

标签: vue.js vuejs2


【解决方案1】:

问题是您将作用域函数分配给 sg 元素的父元素。

在该函数内部,this 不是当前的 Vue 实例,而是 那个 函数的 this。

要解决这个问题,请分配一个箭头函数:

   // ...
   sg.parentElement.addEventListener("wheel", (e) => {
    this.wheel_scale(e, sg);
   });
   // ...

话虽如此,我可以看到您的组件至少有两个侧面问题:

  1. 您似乎有超过 1 个根元素,这是 Vue2 中的一个问题。您可能希望将 &lt;template&gt; 内容包装在一个 &lt;div&gt; 中:
<template>
  <div>
    <div class="count-wheel">{{ scale }}</div>
    ...
    <div id="singapore-map"></div>
  </div>
</template>
  1. 您不应直接与 DOM 交互。通过refs 进行操作:
<div ref="singaporeMap"></div>
  // ...
  mounted() {
    const sg = this.$refs['singaporMap'];
    sg.$el.parentElement.addEventLisnter('wheel', (e) => {
      this.wheel_scale(e.sg);
    })
  }
  // ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 2012-01-01
    相关资源
    最近更新 更多