ahmed
ahmed

Reputation: 15

Create directive to trigger event in Vue.js 3

I want to add an event listener in vue customized directive, that whenever i hover over a q-select in my project it order the options of the q-select in alphabetique order, so i added this directive in main.ts:

 createApp(App)
    .use(Quasar, quasarUserOptions)
    .component("font-awesome-icon", FontAwesomeIcon)
    .use(store)
    .use(router)
    .directive('orderOptions', {
        mounted(el: any) {
            el.addEventListener('mouseenter', () => {
                const options = Array.from(el.querySelectorAll('option'));
                options.sort((a: any, b: any) => (a.textContent ?? '').localeCompare(b.textContent ?? ''));
                options.forEach((option) => el.appendChild(option));
                console.log("options", options);
                el.dispatchEvent(new Event('change'));
            });
        }
    })
    .mount('#app')

and i added v-order-options in my q-select:

          <q-select v-order-options dense outlined v-model="filter.demandStatus" :options="getDemandStatus">
            <template v-slot:append>
              <q-icon v-if="filter.demandStatus" name="cancel" size="xs" class="cursor-pointer" @click.stop.prevent
                @click="filter.demandStatus = undefined" />
              <!--<q-icon name="search" size='xs' />-->
            </template>
          </q-select>

but it didn't work and the options list in the directive remain empty and the combobox still display the orginial options

Upvotes: 0

Views: 94

Answers (0)

Related Questions