自定义组件可使用的方法
一、关闭操作
methods: {/* 其它方法 ... */// 仅监听下一次点击,如果点在外部就关闭oneClickOutside(e) {const panel = this.$refs.panel;const input = this.$refs['search-input'].$el || this.$refs['search-input'];// 点击在浮窗内部、或搜索框本身,都不关if (!panel || panel.contains(e.target) || input.contains(e.target)) return;this.close();},showWindow(info, defaultSortRule, defaultCondition) {this.$nextTick(() => {this.$refs['search-input']?.focus();this.calcPos();// 关键:只在下一轮事件循环注册一次setTimeout(() => {document.addEventListener('mousedown', this.oneClickOutside, { once: true });}, 0);});},close() {this.visible = false;document.removeEventListener('mousedown', this.oneClickOutside);},/* 其他代码 ... */
}
或者
handleOutside(e) {if (e.target.className.indexOf("类名") > -1 &&e.target?.parentNode?.parentNode?.nextElementSibling &&e.target.parentNode.parentNode.nextElementSibling.className.indexOf("类名") > -1) {显示隐藏}// 如果点击的不是弹窗本身,就关闭if ((!this.$el.contains(e.target) ||e.target.className.indexOf("类名") == -1) ) {//关闭操作}},