Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nuxt3 plugin #6

Open
SnakeO opened this issue Mar 15, 2024 · 0 comments
Open

nuxt3 plugin #6

SnakeO opened this issue Mar 15, 2024 · 0 comments

Comments

@SnakeO
Copy link

SnakeO commented Mar 15, 2024

Add the below to /plugins/debounce-directive.js

Then include in nuxt.config.js:
plugins: ['~/plugins/debounce-directive.js']

Finally use as suggested (v-model.lazy):
<input v-model.lazy="sample" v-debounce="delay" />

// plugins/debounce-directive.js
function debounce(fn, delay) {
    let timeoutID = null;
    return function (...args) {
        clearTimeout(timeoutID);
        timeoutID = setTimeout(() => {
            fn.apply(this, args);
        }, delay);
    };
}

export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.vueApp.directive('debounce', {
        mounted(el, binding) {
            if (el.tagName.toLocaleUpperCase() !== 'INPUT') {
                console.warn('v-debounce directive is intended for use with <input> elements and v-model.lazy.');
                return;
            }

            const debounceFunction = debounce(() => {
                // Create and dispatch the 'change' event to trigger v-model.lazy update
                const event = new Event('change', { bubbles: true });
                el.dispatchEvent(event);
            }, parseInt(binding.value, 10) || 500); // Use the directive's value as the debounce delay

            el.addEventListener('input', (event) => {
                event.stopImmediatePropagation(); // Prevent immediate propagation to allow for debouncing

                // Call the debounce function which will emit the 'change' event after delay
                debounceFunction();
            }, true);
        },
        beforeUnmount(el) {
            // Clean up if necessary
            el.removeEventListener('input', el.oninput);
        }
    });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant