防止在vuejs 2中创建addEventListener(“click”)时立即触发它

vulvrdjw  于 2022-12-19  发布在  Vue.js
关注(0)|答案(2)|浏览(208)

我有一个代码,其中我在button上执行click,它会立即触发addEventListener("click"),我希望阻止它立即触发。正常情况下,我可以看到console.log,直到第二次单击,因为当我第一次单击时,我添加了侦听器,第一次单击后,它已经在侦听显示console.logs的单击事件
我该如何预防呢?
这是我的生活代码:

<template>
  <div id="app">
    <button @click="addEvent">add event body</button>
  </div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';

export default {
  name: 'App',
  methods: {
    addEvent() {
      document.body.addEventListener('click', this.doSomething);
    },
    doSomething() {
      console.log('click');
    },
  },
};

https://stackblitz.com/edit/vue-fnxvgg?file=src%2FApp.vue

mrfwxfqh

mrfwxfqh1#

有几个解决方案你可以使用!但我相信stopPropagation()将最适合你!我还添加了click.once到您的addEvent函数,因为我假设您只想调用它来添加事件侦听器!

<template>
  <div id="app">
    <button @click.once="addEvent">add event body</button>
  </div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';

export default {
  name: 'App',
  methods: {
    addEvent(event) {
      event.stopPropagation()
      document.body.addEventListener('click', this.doSomething);
    },
    doSomething() {
      console.log('click');
    },
  },
};
</script>

以下是文档以供参考!https://v2.vuejs.org/v2/guide/events.html#Event-Modifiers https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

mum43rcc

mum43rcc2#

你需要使用stop修饰符来实现这个行为。它和event.stopPropagation()一样,但是它是一种处理事件的有效方法:https://vuejs.org/guide/essentials/event-handling.html#event-modifiers

<template>
  <div id="app">
    <button @click.stop="addEvent">add event body</button>
  </div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue';

export default {
  name: 'App',
  methods: {
    addEvent() {
      console.log('ADDED');
      document.body.addEventListener('click', this.doSomething);
    },
    doSomething() {
      console.log('click');
    },
  },
};
</script>

<style>
body {
  height: 100vh;
  width: 100vw;
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

交互式示例:https://stackblitz.com/edit/vue-nknkm9?file=src%2FApp.vue

相关问题