Vue js custom instruction clicks outside its own element to trigger an event Click outside its own element to hide itself

1. Demand background

Customized search bar, when you click on an element or area outside the red frame, close the red frame, similar to a mask of a pop-up window, click the mask to close the pop-up window.
insert image description here

2. Realize the code

2.1 Create clickOutside.jsa file

Create a new folder directive (specifically place some instruction files), then create a folder click, and put clickOutside.jsthe file under the click folder

/**
* v-clickOutside 点击元素外触发事件
*/

export default {
    
    
  // 初始化指令
  bind(el, binding, vnode) {
    
    
    function clickHandler(e) {
    
    
      // 这里判断点击的元素是否是本身,是本身,则返回
      if (el.contains(e.target)) {
    
    
        return false;
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
    
    
        // 如果绑定了函数 则调用那个函数,此处binding.value就是resetActiveRow方法
        binding.value(e);
      }
    }
    // 给当前元素绑定个私有变量,方便在unbind中可以解除事件监听
    el.__vueClickOutside__ = clickHandler;
    document.addEventListener('click', clickHandler);
  },
  update() {
    
    },
  unbind(el, binding) {
    
    
    // 解除事件监听
    document.removeEventListener('click', el.__vueClickOutside__);
    delete el.__vueClickOutside__;
  }
};

2.2 Register clickOutside.jsthis command file

Under the folder directive, create an index.js file, the code content is as follows

import clickOutside from './click/clickOutside'

const install = function(Vue) {
    
    
  Vue.directive('clickOutside', clickOutside)
}
export default install

2.3 In the main.js file, import instructions

import directive from './directive' // directive
Vue.use(directive)

3. Use it in the vue page file

<div v-click-outside="test">测试</div>
methods: {
    
    
	test() {
    
    
		// 在这里处理点击自身元素外的区域,需要进行什么逻辑操作,如隐藏自身元素等
	}
}

4. Done!

Guess you like

Origin blog.csdn.net/DarlingYL/article/details/130401386