Blog>
Snippets

Touch Events with Vue 3 and Hammer.js

Connect Hammer.js with Vue 3 to handle swipe, tap, and pinch events, providing a better mobile interaction experience.
import { onMounted, onUnmounted } from 'vue';
import Hammer from 'hammerjs';

export default {
    name: 'TouchableComponent',
    props: {},
    setup() {
        // setup a reference to the DOM element
        let hammerInstance;
        const element = ref(null);

        onMounted(() => {
            if (element.value) {
                // instantiate Hammer.js on the element
                hammerInstance = new Hammer(element.value);

                // example: listen to swipe event
                hammerInstance.on('swipe', (event) => {
                    console.log('Swiped!', event);
                });

                // more events here, like 'tap', 'pinch', etc.
            }
        });

        onUnmounted(() => {
            if (hammerInstance) {
                // remove all the Hammer.js events attached to the instance
                hammerInstance.off('swipe');
                // clean up other events if necessary
            }
        });

        return {
            element
        };
    }
};
This Vue 3 component uses Hammer.js to handle touch events. It creates a Hammer instance when the component is mounted and adds event listeners for touch actions such as 'swipe.' When the component is unmounted, it removes the event listeners to prevent memory leaks. Additional events like 'tap' and 'pinch' can be registered in a similar way.