Ųŋĸńōŵņ
Ųŋĸńōŵņ
NNuxt
Created by Ųŋĸńōŵņ on 8/5/2024 in #❓・help
Nuxt 3 directive and updating component data
I made a directive because I would like to be able to detect when a mouse click was outside a specific element. I will use this for a dropdown menu. export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.directive('detect-click-outside', { mounted (el) { el.clickOutsideEvent = function (event) { // // here I check that click was outside the el and his children if (!(el == event.target || el.contains(event.target))) { // and if it did, change data from directive console.log("click is inside") } console.log("click is outside") // update a value (name: clickedOutside) in the component // where this directive is used }; document.body.addEventListener('click', el.clickOutsideEvent) }, }) }) The problem I am facing, and unable to find an answer for on the internet, is how I can update "data" from the component in which the directive is used. For example: const clickedOutside = false; When I click outside, the directive should update the above line in the component used. For example the "mainMenu" component. Does anyone know how I can do that? Sample code of the menu: <script setup> const isDropdwonMenuVisible = ref(false); </script> <template> <div class="mx-auto max-w-screen-2xl flex border-b border-gray:50 py-4 text-sm" v-detect-click-outside> <div class="flex items-center text-lg font-bold cursor-pointer" v-for="(dataKey, dataIndex) in data" :keydata="dataIndex" @click="currentOpened = dataIndex"> {{ dataIndex }} <img src="images/icons/chevron-down-solid.svg" width="12px" class="ml-4" /> </div> {{ currentOpened }} </div> </template>
2 replies