The front-end custom drop-down selection box stepping on the pit - click on the blank part to shrink the drop-down box

Click on the blank part to shrink the drop-down box

The effect after expanding the drop-down box is as follows:
insert image description here
Requirement: Click the input box or the blank part again, and the drop-down box will automatically shrink
the template code as follows:

// 我就简略大概写需要的东西,需要的内容自己添加
<template>
  <div ref="selectTableRef">
    <el-input v-model="value"/>
    <div v-if="isShowTable">
		我是下拉框
	</div>
  </div>
</template>

The js code is as follows:

<script>
  data() {
    
    
  	return {
    
    
  	  value: '',
  	  isShowTable: false,
  	};
  },
  mounted() {
    
    
    // 挂载全局监听, 用document或window都行,但要跟removeEventListener一样, 注意closePanel不可以带参数
    document.addEventListener("click", this.closePanel);
  },
  beforeDestroy() {
    
    
    // 页面销毁前记得移除监听,注意closePanel不可以带参数,跟addEventListener的方法是一样的
    document.removeEventListener("click", this.closePanel);
  },
  methods: {
    
    
  closePanel(e) {
    
    
  	  // 注意: 要在需要下拉框和输入框的父元素添加 ref="selectTableRef"
      const selectTableRef = this.$refs.selectTableRef;
      // selectTableRef里是否包含点击的元素,不包含点击的元素就隐藏面板
      if (!selectTableRef.contains(e.target)) {
    
    
        this.isShowTable = false;
      }
    },
  }
</script>

Guess you like

Origin blog.csdn.net/qq_51741730/article/details/128565108