Search code examples
javascriptvue.jseventsvuejs3vuetify.js

How to prevent the click event from a children not rendered by vue to bubble up to the parent


Link to codepen

The previous codepen allows you to resize vuetify table rows. Unfortunately with sortable: true the click event from the "hanlde" div bubbles up to the header row and triggers the toggleSort function from the default vuetify table headers. I don't want to override the headers slot so I cannot use @click.self="toggleSort", while adding e.stopPropagation() to the addEventListener doesn't work. Any idea?

You can notice the problem when you drag far enough to move the cursor outside of the div handle before releasing the mouse button. Here is a video: https://youtu.be/WsLPF-lpdDc


Solution

  • Just temporarily disable sorting when dragging:

    --- a/app.vue
    +++ b/app.vue
    @@ -9,20 +9,21 @@
     <script setup lang="ts">
       import { ref, nextTick } from 'vue'
    
    +  const sortable = ref(true)
       const headers = ref([
         {
           title: 'Dessert (100g serving)',
           align: 'end',
    -      sortable: true,
    +      sortable,
           value: 'name',
           width: undefined,
           maxWidth: undefined,
         },
    -    { title: 'Calories', sortable: true, align: 'end', value: 'calories' },
    -    { title: 'Fat (g)', sortable: true, align: 'end', value: 'fat' },
    -    { title: 'Carbs (g)', sortable: true, align: 'end', value: 'carbs' },
    -    { title: 'Protein (g)', sortable: true, align: 'end', value: 'protein' },
    -    { title: 'Iron (%)', sortable: true, align: 'end', value: 'iron' },
    +    { title: 'Calories', sortable, align: 'end', value: 'calories' },
    +    { title: 'Fat (g)', sortable, align: 'end', value: 'fat' },
    +    { title: 'Carbs (g)', sortable, align: 'end', value: 'carbs' },
    +    { title: 'Protein (g)', sortable, align: 'end', value: 'protein' },
    +    { title: 'Iron (%)', sortable, align: 'end', value: 'iron' },
       ])
       const desserts = ref([
         {
    @@ -188,6 +189,8 @@
               divEvent: MouseEvent | undefined
    
             div.addEventListener('mousedown', function (e) {
    +          sortable.value = false
    +
               divEvent = e
               curCol = (e.target as HTMLDivElement).parentElement as HTMLTableColElement
               pageX = e.pageX
    @@ -252,6 +255,8 @@
                 divEvent = undefined
               }
             })
    +
    +        setTimeout(() => sortable.value = true, 0)
           }
    
           function createDiv(height: number): HTMLDivElement {