干燥机配套车间生产管理系统/云平台前端
baoshiwei
2023-03-10 1fb197352b6a263646e4ccd3ed1c7854ede031dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<template>
  <a-select v-bind="bindProps" @change="onChange" @search="onSearch" />
</template>
 
<script lang="ts">
  import { propTypes } from '/@/utils/propTypes';
  import { defineComponent, ref, watch, computed } from 'vue';
 
  // 可以输入的下拉框(此组件暂时没有人用)
  export default defineComponent({
    name: 'JSelectInput',
    props: {
      options: propTypes.array.def(() => []),
    },
    emits: ['change', 'update:value'],
    setup(props, { emit, attrs }) {
      // 内部 options 选项
      const options = ref<any[]>([]);
      // 监听外部 options 变化,并覆盖内部 options
      watch(
        () => props.options,
        () => {
          options.value = [...props.options];
        },
        { deep: true, immediate: true }
      );
      // 合并 props 和 attrs
      const bindProps: any = computed(() =>
        Object.assign(
          {
            showSearch: true,
          },
          props,
          attrs,
          {
            options: options.value,
          }
        )
      );
 
      function onChange(...args: any[]) {
        deleteSearchAdd(args[0]);
        emit('change', ...args);
        emit('update:value', args[0]);
      }
 
      function onSearch(value) {
        // 是否找到了对应的项,找不到则添加这一项
        let foundIt =
          options.value.findIndex((option) => {
            return option.value.toString() === value.toString();
          }) !== -1;
        // !!value :不添加空值
        if (!foundIt && !!value) {
          deleteSearchAdd(value);
          // searchAdd 是否是通过搜索添加的
          options.value.push({ value: value, searchAdd: true });
          //onChange(value,{ value })
        } else if (foundIt) {
          onChange(value);
        }
      }
 
      // 删除无用的因搜索(用户输入)而创建的项
      function deleteSearchAdd(value = '') {
        let indexes: any[] = [];
        options.value.forEach((option, index) => {
          if (option.searchAdd) {
            if ((option.value ?? '').toString() !== value.toString()) {
              indexes.push(index);
            }
          }
        });
        // 翻转删除数组中的项
        for (let index of indexes.reverse()) {
          options.value.splice(index, 1);
        }
      }
 
      return {
        bindProps,
        onChange,
        onSearch,
      };
    },
  });
</script>
 
<style scoped></style>