vue.jsvuejs3vueusevuejs3-composition-api

VueUse onClickOutside does not work with right click


I am currently trying to use onClickOutside but it only works when i click outside with the left mouse button. I need to get this working for the right mouse button too.

Any solution for this? Maybe i missed some option for the function.


Solution

  • VueUse does not work here, because no click event is raised. Instead the contextmenu event will be raised here.

    Try something like this:

    import type { Ref } from 'vue'
    
    export const useClickOutside = (target: Ref<HTMLElement>, handler: () => void) => {
      const { isOutside } = useMouseInElement(target)
    
      const onClick = () => {
        if (isOutside.value) {
          handler()
        }
      }
    
      onMounted(() => {
        document.addEventListener('click', onClick)
        document.addEventListener('contextmenu', onClick)
      })
    
      onUnmounted(() => {
        document.removeEventListener('click', onClick)
        document.removeEventListener('contextmenu', onClick)
      })
    }