自定义指令:点击某个容器外触发事件,比如点击弹窗外,关闭弹窗(Vue)

   <template>
        <div v-clickoutside="clickEventspace">
          <ul>
            <li>显示1li>
            <li>显示2li>
          ul>
        div>
  template>
<script>
// 提交测试
export default {
  name: "testContent3",
  //实现点击div元素外出发事件
  directives: {
    clickoutside: {
      bind: function (el, binding, vnode) {
        function documentHandler(e) {
          if (el.contains(e.target)) {
            return false;
          }
          if (binding.expression) {
            binding.value(e);
          }
        }
        el.__vueClickOutside__ = documentHandler;
        document.addEventListener("click", documentHandler);
      },
      unbind: function (el, binding) {
        document.removeEventListener("click", el.__vueClickOutside__);
        delete el.__vueClickOutside__;
      },
    },
  },
  data() {
    return {
    };
  },
  methods: {
    clickEventspace() {
      console.log("点击了div元素外");
      // 隐藏上下文菜单
      this.contextMenu.show = false;
    },
  },
};
</script>

你可能感兴趣的:(vue.js,javascript,前端)