在这里插入图片描述

自定义指令 v-click-outside

文档

v-click-outside 可以实现点击外部区域才触发事件

实现代码

<template>
  <div class="TestClickOutside">
    <div
      class="TestClickOutside__inner"
      v-click-outside="handleClickOutside"
    ></div>
  </div>
</template>

<script>
// created at 2022-08-25
export default {
  name: 'TestClickOutside',

  props: {},

  components: {},

  data() {
    return {}
  },

  directives: {
    'click-outside': {
      bind(el, binding, vnode) {
        console.log('bind')
        function eventHandler(e) {
          if (el.contains(e.target)) {
            return false
          }
          // 如果绑定的参数是函数,正常情况也应该是函数,执行
          if (binding.value && typeof binding.value === 'function') {
            binding.value(e)
          }
        }
        // 用于销毁前注销事件监听
        el.__click_outside__ = eventHandler
        // 添加事件监听
        document.addEventListener('click', eventHandler)
      },

      unbind(el, binding, vnode) {
        console.log('unbind')

        // 移除事件监听
        document.removeEventListener('click', el.__click_outside__)
        // 删除无用属性
        delete el.__click_outside__
      },
    },
  },

  methods: {
    handleClickOutside() {
      console.log('handleClickOutside')
    },
  },

  created() {},
}
</script>

<style lang="less"></style>

<style lang="less" scoped>
.TestClickOutside__inner {
  width: 100px;
  height: 100px;
  background-color: #666666;
}
</style>

vue-click-outside

文档

安装

$ npm install vue-click-outside
<template>
  <div class="TestClickOutside">
    <div
      class="TestClickOutside__inner"
      v-click-outside="handleClickOutside"
    ></div>
  </div>
</template>

<script>
// created at 2022-08-25
import ClickOutside from 'vue-click-outside'

export default {
  name: 'TestClickOutside',

  props: {},

  components: {},

  data() {
    return {}
  },

  directives: { ClickOutside },

  computed: {},

  methods: {
    handleClickOutside() {
      console.log('handleClickOutside')
    },
  },

  created() {},
}
</script>

<style lang="less"></style>

<style lang="less" scoped>
.TestClickOutside__inner {
  width: 100px;
  height: 100px;
  background-color: #666666;
}
</style>

参考
vue 解除鼠标的监听事件的方法

Logo

前往低代码交流专区

更多推荐