vue custom directive 로 메뉴(드롭다운 등) 밖에 눌렀을때 꺼지는 기능

강참치·2022년 10월 17일
0

드롭다운 메뉴 개발중,

밖을 눌러도 꺼지게 하는 필요성을 느껴 제작

Vue.directive('click-outside', {
  bind: function (el, binding, vnode) {
    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, call method provided in attribute value
        vnode.context[binding.expression](event)
      }
    }
    document.body.addEventListener('click', el.clickOutsideEvent)
  },
  unbind: function (el) {
    document.body.removeEventListener('click', el.clickOutsideEvent)
  }
})
profile
참치입니다

0개의 댓글