vue.js: how to handle click and dblclick events on same element

题意:Vue.js:如何在同一个元素上处理点击和双击事件

问题背景:

I have a vue component with separate events for click/dblclick. Single click (de)selects row,

我有一个 Vue 组件,分别为点击和双击设置了事件。单击(取消)选择行,

dblclick opens edit form.

双击会打开编辑表单。

<ul class="data_row"
  v-for="(row,index) in gridData"
  @dblclick="showEditForm(row,$event)"
  @click="rowSelect(row,$event)"
>

Doing it like this, i get 3 events fired on double click. Two click events and lastly one dblclick. Since the click event fires first , is there a way (short of deferring click event for a fixed amount of ms) for stopping propagation of click event on double click ?

这样做的话,我在双击时会触发三个事件:两个点击事件和最后一个双击事件。由于点击事件先触发,是否有办法(除了延迟点击事件一段固定时间)在双击时停止点击事件的传播?

Fiddle here

问题解决:

As suggested in comments, You can simulate the dblclick event by setting up a timer for a certain period of time(say x).

正如评论中所建议的,你可以通过设置一个定时器,在一定时间内(比如 x 秒)来模拟双击事件。

  • If we do not get another click during that time span, go for the single_click_function().   如果在这个时间段内没有再发生一次点击,就调用 `single_click_function()`。
  • If we do get one, call double_click_function().   如果发生了第二次点击,则调用 `double_click_function()`。
  • Timer will be cleared once the second click is received.   一旦收到第二次点击,计时器将被清除。
  • It will also be cleared once x milliseconds are lapsed.   一旦经过 x 毫秒,计时器也将被清除。

See below code and working fiddle.

请查看下面的代码和工作示例。

new Vue({
    el: '#app',
    data: {
        result: [],
        delay: 700,
        clicks: 0,
        timer: null
    },    
     mounted: function() {
        console.log('mounted');
     },      
     methods: {
        oneClick(event) {
          this.clicks++;
          if (this.clicks === 1) {
            this.timer = setTimeout( () => {
              this.result.push(event.type);
              this.clicks = 0
            }, this.delay);
          } else {
             clearTimeout(this.timer);  
             this.result.push('dblclick');
             this.clicks = 0;
          }         
        }      
     }
});

猜你喜欢

转载自blog.csdn.net/suiusoar/article/details/143485438