vue实现可输入可下拉选择的组件

效果图:
vue实现可输入可下拉选择的组件_第1张图片

组件:

<template>
  <div style="position: relative" class="custom-select-dropdown">
    <Input
      v-model="keyWord" clearable
      :placeholder="placeholder" @on-focus="focusNotarialCode"
      @on-change="changeValue"
    />
    <div
      v-show="isShowDrownItem && optionList && optionList.length>0" class="ivu-select-dropdown"
      style="width: 100%"
    >
      <ul class="ivu-select-dropdown-list">
        <li
          v-for="(item, idx) in optionList" :key="item.value + idx"
          class="ivu-select-item" @click="selectedItem(item)"
        >{{ item.nameZh}}li>
      ul>
    div>
  div>
template>

<script>
export default {
  name: 'CustomSelect',
  props: {
    selected: {
      type: [String, Number]
    },
    placeholder: {
      type: String,
      default: ''
    },
    keyName: {
      type: String
    },
    optionList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      isShowDrownItem: false,
      keyWord: ''
    }
  },
  watch: {
    optionList(newVal) {
      console.log('optionList', newVal)
    },
    selected: {
      immediate: true,
      handler(newVal) {
        console.log('selected', newVal)
        this.keyWord = newVal
      }
    }
  },
  mounted() {
  },
  beforeDestroy() {
    document.removeEventListener('click', this.hidePopClick)
  },
  methods: {
    hidePopClick(e) {
      const path = e.path || (e.composedPath && e.composedPath())
      const flag = path.some(dom => dom.className && dom.className.indexOf('custom-select-dropdown') !== -1)
      if (!flag) {
        this.isShowDrownItem = false
      }
    },
    focusNotarialCode() {
      this.isShowDrownItem = true
      document.addEventListener('click', this.hidePopClick)
    },
    selectedItem(item) {
      console.log('选中', item)
      this.keyWord = this.keyName ? item[this.keyName] : item.value
      this.$emit('selectedItem', this.keyWord)
      this.isShowDrownItem = false
    },
    changeValue() {
      console.log('变更的值', this.keyWord)
      this.$emit('selectedItem', this.keyWord)
    }
  }
}
script>

<style scoped>

style>

组件使用:

            <custom-select
              key="notarialOffice"
              :selected="formValidate.fileSubTypeName"
              placeholder="请输入材料名称"
              :option-list="notarialOfficeList"
              key-name="nameZh"
              @selectedItem="getSelectedItem($event,'fileSubTypeName')"
            />

const notarialOfficeList = [
    {
        "id": 1337,
        "nameZh": "张三",
        "nameEn": "zhangsan",
        "value": "CP",
    },
    {
        "id": 1338,
        "nameZh": "李四",
        "nameEn": "lisi",
        "value": "CD",
    }
]


    getSelectedItem(val, key) {
      this.formValidate[key] = val || ''
    }

你可能感兴趣的:(vue,vue.js,javascript,前端)