a5zima
a5zima

Reputation: 114

How to handle touchEvents with Vue?

Is it possible to handle touchEvents with Vue3 without external library?

My need is that the element can be moved (drag and drop in another place) by touch. The elements themselves are rendered using v-for. I implemented mouse control without problems, but with touch I got stuck for a day!

I've found only one library for that: https://github.com/robinrodricks/vue3-touch-events

But I really can't understand where I have to put UDM module and how to execute installation steps like that: "You need to include the UMD script of this plugin and you do not need to register this plugin with vue.js."

I can't believe that such popular framework as Vue3 haven't native touch handlers, so I want to ask an advice.

Upvotes: 4

Views: 25025

Answers (2)

renosytr
renosytr

Reputation: 56

I recommend to use Vueuse instead of HammerJS especially if your project uses Vue 3 with Vite, because it does not support the minifying process during the build process.

The main concept is pretty stright forward. Here I give you a snippet example:

import { useSwipe } from '@vueuse/core'
import { ref } from 'vue'

const refWindow = ref(null)
const { direction } = useSwipe(
    refWindow, { // your ref element 
        onSwipe() {
            if(direction.value === "DOWN"){
                handleSwipe('swipedown') // your event handler
            } else if (direction.value === "UP"){
                handleSwipe('swipeup') // your event handler
            }
        },
    }
)

Upvotes: 3

Alicia Sykes
Alicia Sykes

Reputation: 7107

Touch events are supported natively in Vue, in the same way that they are in JavaScript. But the dragging or swiping functionality, you will need to either build yourself, or use a third-party plugin (like hammer.js).

You can use touch events in a similar way to mouse up/ down. For example:

<MyComponent
  @mousedown="startDrag(item)"
  @mouseup="endDrag(item)"
  @mousemove="startDrag(item)"
  @touchstart="startDrag(item)"
  @touchend="endDrag(item)"
  @touchmove="endDrag(item)"        
/>

Upvotes: 12

Related Questions