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.
2. Realize the code
2.1 Create clickOutside.js
a file
Create a new folder directive (specifically place some instruction files), then create a folder click, and put clickOutside.js
the 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.js
this 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() {
// 在这里处理点击自身元素外的区域,需要进行什么逻辑操作,如隐藏自身元素等
}
}