基于element-ui 2.x版本input写的input模糊查询组件

最近做项目中,用到了input框中的模糊查询,由于项目中用到了element-ui,于是就去查看了当中的selecct组件,其中通过添加 filterable  remote  reserve-keyword  remote-method 等相关属性即可实现模糊查询效果,自己也根据效果写了基于 el-input 的模糊查询效果,相关组件代码如下:
<template>
  <!-- 基于element-ui2.x版本input写的input模糊查询组件 -->
  <div>
    <div ref="selectOption">
      <el-input
        v-model="selectInputVal"
        :placeholder="placeholder"
        @input="inputHandle"
      ></el-input>
      <ul
        class="options"
        v-if="optionsList.length && selectInputVal.length > 0"
        :style="'width:' + selectOptionWidth + 'px;top:' + selectOptionTop + 'px'"
      >
        <li
          v-for="item in optionsList"
          :key="item.id"
          @click="clickOption(item)"
        >
          {{ item.label }}
        </li>
      </ul>
    </div>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      selectInputVal: this.value,
      selectOptionWidth: 0,
      selectOptionTop: 0,
    };
  },
  methods: {
    getOptionsOffset() {
      this.selectOptionWidth = this.$refs.selectOption.children[0].offsetWidth;
      this.selectOptionTop = this.$refs.selectOption.children[0].offsetHeight;
    },
    inputHandle(value) {
      this.$emit("selectInputHandle", value);
    },
    clickOption(info) {
      this.$emit("selectOptionItem", info);
    },
    inputBlurHandle() {
      this.$emit("selectBlurHandle");
    },
  },
  created() {},
  mounted() {
    this.getOptionsOffset();
    document.addEventListener("click", this.inputBlurHandle);
  },
  props: {
    value: {
      default: "",
    },
    placeholder: {
      type: String,
      default: "",
    },
    optionsList: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    value(val) {
      this.selectInputVal = val;
    },
  },
  beforeDestroy() {
    document.removeEventListener("click", this.inputBlurHandle);
  },
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  list-style: none;
}
ul.options {
  position: absolute;
  left: 0;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  z-index: 99999;
  background-color: #fff;
  box-sizing: border-box;
  max-height: 300px;
  overflow-y: auto;
}
li {
  cursor: pointer;
  border-bottom: 1px solid #dcdfe6;
  user-select: none;
}
li:hover {
  background-color: #dcdfe6;
}
li:last-child {
  border-bottom: none;
}
</style>

 

posted @ 2022-06-19 16:37  ~逍遥★星辰~  阅读(374)  评论(0编辑  收藏  举报