Migrating "detect click outside" custom directive from Vue 2 to Vue 3
Asked Answered
M

4

17

Based on this question Detect click outside element and this answer https://stackoverflow.com/a/42389266, I'm trying to migrate the directive from Vue 2 to Vue 3. It seems that binding.expression and vnode.context not exists more. How can I make it work?

app.directive('click-outside', {
    beforeMount (el, binding, vnode) {
        el.clickOutsideEvent = function (event) {
            if (!(el === event.target || el.contains(event.target))) {
                vnode.context[binding.expression](event);
            }
        };
        document.body.addEventListener('click', el.clickOutsideEvent);
    },
    unmounted (el) {
        document.body.removeEventListener('click', el.clickOutsideEvent);
    }
});
Marital answered 13/9, 2020 at 10:47 Comment(2)
I don't know your specific use case, but many time people are wanting to use a click outside event they are not taking accessibility into account in that a keyboard only user may need the same functionality to happen when a blur event or "focus" outside happens. If you don't want to reinvent the wheel and you're able to add another library, this is a great library I've used in the past to achieve both click outside and blur outside. npmjs.com/package/vue-outside-eventsKlink
@Klink thanks for your suggestion, however the library shown is for vue 2Marital
T
23

You can use binding.value instead like this:

const { createApp } = Vue;

const highlightEl = (color ) => (event, el) => {
  if (el) {
    el.style.background = color;
  } else {
    event.target.style.background = color;
  }
}
const clearHighlightEl = (event, el) => {
  if (el) {
    el.style.background = '';
  } else {
    event.target.style.background = '';
  }
}

const app = Vue.createApp({
  setup() {
    return {
      highlightEl,
      clearHighlightEl
    }
  }
})

app.directive('click-outside', {
  mounted(el, binding, vnode) {
    el.clickOutsideEvent = function(event) {
      if (!(el === event.target || el.contains(event.target))) {
        binding.value(event, el);
      }
    };
    document.body.addEventListener('click', el.clickOutsideEvent);
  },
  unmounted(el) {
    document.body.removeEventListener('click', el.clickOutsideEvent);
  }
});

app.mount('#app')
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>

<div id="app">
  <h1 v-click-outside="highlightEl('yellow')" @click="clearHighlightEl">Element 1</h1>
  <p v-click-outside="highlightEl('#FFCC77')" @click="clearHighlightEl">Element 2</p>
</div>
Thetes answered 15/9, 2020 at 22:22 Comment(0)
N
18

out of the context, there's an easier way in vue3 with composition.

Link to Vueuse ClickOutside (Vue 3)

Link to Vueuse ClickOutside(Vue 2)

<template>
  <div ref="target">
    Hello world
  </div>
  <div>
    Outside element
  </div>
</template>

<script>
import { ref } from 'vue'
import { onClickOutside } from '@vueuse/core'

export default {
  setup() {
    const target = ref(null)

    onClickOutside(target, (event) => console.log(event))

    return { target }
  }
}
</script>
Nostril answered 23/4, 2021 at 9:47 Comment(0)
F
1

you can use ref to find out if the element contains the element clicked

<template>
    <div ref="myref">
        Hello world
    </div>
    <div>
        Outside element
    </div>
</template>

<script>

export default {

    data() {
        return {
            show=false
        }
    },
    mounted(){
        let self = this;
        document.addEventListener('click', (e)=> {
            if (self.$refs.myref !==undefined && self.$refs.myref.contains(e.target)===false) {
                //click outside!
                self.show = false;
            }
        })
    }
}
</script>
Felisha answered 24/5, 2022 at 22:10 Comment(0)
K
1

hook solution:

<template>
  <p ref="myP">does click outside of p : {{ isClickOutside ? 'Yes' : 'No' }}</p>
</template>

<script lang="ts" setup>
import { useOnClickOutside } from './useOnClickOutside'

const myP = ref()
const isClickOutside = useOnClickOutside(myP, () => {
  console.log('click outside of p')
})
</script>

useOnClickOutside.js

import { onBeforeUnmount, onMounted, ref } from 'vue'
// DOMRef is dom by ref
export function useOnClickOutside(DOMRef = null, callback) {
  const isClickOutside = ref(false)
  function handleClick(event) {
    if (DOMRef?.value && !DOM.value.contains(event.target)) {
      callback()
      isClickOutside.value = true
      return
    }
    isClickOutside.value = false
  }

  onMounted(() => {
    document.addEventListener('mousedown', handleClick)
  })

  onBeforeUnmount(() => {
    document.removeEventListener('mousedown', handleClick)
  })
  return isClickOutside
}

component solution:

use:

<template>
   <OnClickOutside :clickOutside="conosole.log('log when clickoutside of div')">
     <div>when clicked outside div</div>
   </OnClickOutside>
</template>

vue2 solution:

<script>
  export default {
    name: 'OnClickOutside',
    props: ['clickOutside'],
    mounted() {
      const listener = e => {
        if (e.target === this.$el || this.$el.contains(e.target)) {
          return
        }
        this.clickOutside()
      }

      document.addEventListener('click', listener)
      this.$once('hook:beforeDestroy', () => document.removeEventListener('click', listener))
    },
    render() {
      return this.$slots.default[0]
    },
  }
</script>

vue3:

<script>
  import { getCurrentInstance, onMounted, onBeforeUnmount, ref, defineComponent } from 'vue'
  export default defineComponent({
    name: 'OnClickOutside',
    props: ['clickOutside'],
    setup(props, { emit, attrs, slots }) {
      const vm = getCurrentInstance()
      const listener = event => {
        const isClickInside = vm.subTree.children.some(element => {
          const el = element.el
          return event.target === el || el.contains(event.target)
        })
        if (isClickInside) {
          console.log('clickInside')
          return
        }
        props.clickOutside && props.clickOutside()
      }
      onMounted(() => {
        document.addEventListener('click', listener)
      })
      onBeforeUnmount(() => {
        document.removeEventListener('click', listener)
      })
      return () => slots.default()
    },
  })
</script>
Kopaz answered 18/7, 2022 at 19:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.