zerolab-fe / one-question-per-day

每天一个小问题
21 stars 7 forks source link

Vue 指令判断当前点击是否为 Dom 以外的位置 #63

Open wlin00 opened 4 years ago

wlin00 commented 4 years ago

开发中遇到的小需求,需要监听Dom以外位置的点击事件

全局使用

    Vue.directive('clickOutside', {
      bind (el, binding, node) {
        el.event = function (event) {
        // 判断当前点击是否非Dom范围
          if (el !== event.target && !el.contains(event.target)) {
          node.context[binding.expression](event)
          }
        }
        document.body.addEventListener('click', el.event, true)
      },
      unbind (el) {
        document.body.removeEventListener('click', el.event, true)
      }
    })

组件范围内使用

     directives: {
        clickOutside: {
          bind (el, binding, node) {
            el.event = function (event) {
              // 判断当前点击是否非Dom范围
              if (el !== event.target && !el.contains(event.target)) {
                node.context[binding.expression](event)
              }
            }
            document.body.addEventListener('click', el.event, true)
          },
          unbind (el) {
            document.body.removeEventListener('click', el.event,true)
          }
        }
      }

使用

    <div v-click-outside="switchMode"></div>

ReactHooks版本

GleanCoder1116 commented 4 years ago

image

wlin00 commented 4 years ago

已修改