Skip to content

Instantly share code, notes, and snippets.

@bryandidur
Last active June 2, 2019 20:13
Show Gist options
  • Save bryandidur/277baf9cacd487f6139f0d2b6c9add55 to your computer and use it in GitHub Desktop.
Save bryandidur/277baf9cacd487f6139f0d2b6c9add55 to your computer and use it in GitHub Desktop.
Swipe Callback Vue Component

Add the Hammer JS library to your project (https://hammerjs.github.io)

<script src="http://hammerjs.github.io/dist/hammer.min.js"></script>

Code

Vue.component('swipeable', {
    props: {
        event: {
            type: String,
            default: 'swipedown'
        },
        callback: {
            type: Function,
            default: () => {},
        },
        supportKey: {
            type: Boolean,
            default: true,
        },
        supportKeyCode: {
            type: Number,
            default: 17, // Control
        },
    },
    data() {
        return {
            manager: {},
            isSupportKeyActive: false,
        };
    },
    computed: {
        slotElement() {
            return this.$slots.default[0].elm;
        },
    },
    mounted() {
        this.manager = new Hammer.Manager(this.slotElement, {
            cssProps: { userSelect: this.supportKey ? 'auto' : 'none' },
            recognizers: [
                [Hammer.Swipe, { direction: Hammer.DIRECTION_ALL }],
            ],
        });

        this.manager.on(this.event, this.handleEvent);

        if (this.supportKey) {
            document.addEventListener('keydown', this.handleSupportKeyDown);
            document.addEventListener('keyup', this.handleSupportKeyUp);
        }
    },
    beforeDestroy() {
        this.manager.off(this.event, this.handleEvent);

        if (this.supportKey) {
            document.removeEventListener('keydown', this.handleSupportKeyDown);
            document.removeEventListener('keyup', this.handleSupportKeyUp);
        }
    },
    methods: {
        handleEvent(event) {
            if (this.supportKey && ! this.isSupportKeyActive) return;

            this.callback(event);
        },
        handleSupportKeyDown(event) {
            if (event.keyCode == this.supportKeyCode) {
                this.isSupportKeyActive = true;
                this.slotElement.style.userSelect = 'none';
            }
        },
        handleSupportKeyUp(event) {
            if (event.keyCode == this.supportKeyCode) {
                this.isSupportKeyActive = false;
                this.slotElement.style.userSelect = 'auto';
            }
        },
    },
    template: `
        <div>
            <slot>
                <span></span>
            </slot>
        </div>
    `,
});

Usage

Adding the markup
<swipeable event="swipedown" :callback="fetchData" :support-key="true" support-key-code="17">
    <table>...</table>
</swipeable>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment