1. The background

I wrote a tooltip component in my business. The initial requirement was simply to enter the page and display it, and then hide it for 3 seconds. The latter component, when used in other scenarios, requires the user to customize the hiding timing and perform the callback when the tooltip is hidden.

At this point, it occurred to me that elements such as Select and popover perform hiding when the user clicks outside of the component.

2. Implementation instructions

Use the VUE custom directive to bind the TouchStart event to the Document within the directive

//outside.js

const ctx = "@@clickoutsideContext";

export default {
  bind(el, binding, vnode) {
    const ele = el;
    const documentHandler = (e) = > {
      if(! vnode.context || ele.contains(e.target)) {return false;
      }
      // Call the instruction callback
      if (binding.expression) {
        vnode.context[el[ctx].methodName](e);
      } else{ el[ctx].bindingFn(e); }}// Add methods to ele
    ele[ctx] = {
      documentHandler,
      methodName: binding.expression,
      bindingFn: binding.value,
    };

	setTimeout((a)= > {
	  document.addEventListener('touchstart', documentHandler); // Bind events for document
	});
  },
  update(el, binding) {
    const ele = el;
    ele[ctx].methodName = binding.expression;
    ele[ctx].bindingFn = binding.value;
  },
  unbind(el) {
	document.removeEventListener('touchstart', el[ctx].documentHandler); / / unbundling
	deleteel[ctx]; }};Copy the code

3. Use instructions

// demo.vue

<div v-clickoutside="handleOutside"></div>

import outside from './outside';

export default {
    directives: { clickoutside: outside },
    methods: {
        handleOutside(e) {},
    },
};
Copy the code