vue 3.0 +ant-design / select 二次封装

SelectSearch 组件

<template>
  <a-select
    v-model:value="valueId"
    v-bind="getBindValues"
    show-search
    :filter-option="false"
    :options="options"
    @search="handleSearch"
    @popupScroll="popupScroll"
    @change="handelChange"
    style="min-width: 200px"
  >
    <template #notFoundContent>
      <a-spin size="small" v-if="fetching" />
      <a-empty v-else />
    </template>
    <template #dropdownRender="{ menuNode: menu }" v-if="isSelectAll">
      <v-nodes :vnodes="menu" />
      <a-divider style="margin: 4px 0" />
      <div
        style="
          padding: 4px 8px;
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          width: 100%;
        "
        @mousedown="(e) => e.preventDefault()"
      >
        <a-button type="link" @click="selectAll">全选</a-button>
        <a-button type="link" @click="clearAll">清空</a-button>
      </div>
    </template>
    <template #[item]="data" v-for="item in Object.keys($slots)" :key="item">
      <slot :name="item" v-bind="data || {}"></slot>
    </template>
  </a-select>
</template>
<script>
import { defineComponent, reactive, toRefs } from 'vue';
import { Select } from 'ant-design-vue';
import { debounce } from 'lodash-es';
export default defineComponent({
  name: 'SelectSearch',
  components: {
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
  },
  props: Object.assign(Select.props, {
    data: {
      type: Function,
      default: () => {},
    },
    fieldNames: {
      type: Object,
      default: () => {
        return { label: 'label', value: 'value', options: 'options' };
      },
    },
    allowClear: {
      type: Boolean,
      default: true,
    },
    pager: {
      type: Object,
      default: {},
    },
    searchKey: {
      type: String,
      default: '',
    },
    isSelectAll: {
      type: Boolean,
      default: false,
    },
  }),

  setup(props, { emit }) {
    const getBindValues = computed(() => {
      let propsData = {
        class: 's-select-warp',
        ...props,
      };
      delete propsData['onUpdate:value'];
      return propsData;
    });

    const valueId = computed({
      get: () => props.value,
      set: (val) => {
        emit('update:value', val);
      },
    });

    const state = reactive({
      options: [],
      fetching: false,
      total: 0,
      fetchId: 0,
      parmas: {},
      lastFetchId: 0,
      pager: props.pager || {},
    });

    // 重置
    const init = () => {
      if (props.searchKey) state.parmas[props.searchKey] = '';
      if (state.pager.pageNum) state.pager.pageNum = 1;
      state.options = [];
      getList();
    };

    // 接口获取数据方法
    const getList = () => {
      state.fetching = true;
      if (props.data) {
        const result = props.data(Object.assign(state.pager, state.parmas));
        result.then((res) => {
          if (res.code === 0) {
            state.total = res.total;
            state.options = state.options.concat(res.data);
            state.fetching = false;
          }
        });
      }
    };

    // 有分页时下拉加载数据
    const popupScroll = (e) => {
      if (state.pager.pageNum) {
        const { target } = e;
        const scrllHeight = target.scrollHeight - target.scrollTop;
        const clientHeight = target.clientHeight;
        // 下拉框不下拉的时候
        if (scrllHeight === 0 && clientHeight === 0) {
          state.pager.pageNum = 1;
        } else if (scrllHeight - clientHeight == 0) {
          // 下拉到底部时
          if (state.options.length < state.total) {
            // 如果滑到底部,则加载下一页
            state.pager.pageNum++;
            getList();
          }
        }
      }
    };

    // 清空时重新获取数据
    const handelChange = (value) => {
      if (!value) {
        init();
      }
    };

    // 节流查询
    const handleSearch = debounce((value) => {
      state.lastFetchId += 1;
      if (state.pager.pageNum) state.pager.pageNum = 1;
      if (props.searchKey) state.parmas[props.searchKey] = value; // 查询Key
      state.fetchId = state.lastFetchId;
      state.options = [];
      if (state.fetchId !== state.lastFetchId) {
        return;
      }
      getList();
    }, 800);

    // 全选
    const selectAll = () => {
      let vals = state.options.map((item) => item[props.fieldNames.value]);
      emit('update:value', vals);
    };

    // 清空
    const clearAll = () => {
      emit('update:value', []);
    };

    getList();
    return {
      ...toRefs(state),
      handleSearch,
      handelChange,
      getList,
      popupScroll,
      getBindValues,
      valueId,
      selectAll,
      clearAll,
    };
  },
});
/**
 * selectDictTypeList : 调用后台接口方法 Promise
 
 * 无分页 <SelectSearch:data="selectDictTypeList"v-model:value="testValue1"></SelectSearch>

 * 有分页  <SelectSearch  :data="selectDictTypeList" v-model:value="testValue1" :pager="{ pageSize:1,pageNum:10 }"></SelectSearch>
 
 * 指定label/key <SelectSearch :data="selectDictTypeList" v-model:value="testValue1" :fieldNames="{label: 'dictName', value: 'dictType', options: 'options'}"></SelectSearch>

 * 全选/清空  <SelectSearch :data="selectDictTypeList" v-model:value="testValue1" mode="multiple" :isSelectAll="true"></SelectSearch>
  
 */
</script>

<a-form-item label="权限字典名" name="dictHeader">
                <SelectSearch
                  :data="selectDictTypeList"
                  v-model:value="item.dictHeader"
                  searchKey="dictName"
                  :fieldNames="{
                    label: 'dictName',
                    value: 'dictType',
                    options: 'options',
                  }"
                  @change="dictSelect(index)"
                >
                  <template #option="row">
                    {{ row.dictName }} + '自定义'
                  </template>
                </SelectSearch>
              </a-form-item>
### Vue2 + Ant-Design-Vue + Formily V2 示例 以下是基于 `Vue2` 和 `Ant-Design-Vue` 的 `Formily V2` 实现的一个示例,包含筛选功能(输入框、选择框、单选按钮、Select 封装组件)以及表格展示。 #### 安装依赖 确保已安装以下依赖项: ```bash npm install vue@2.5.22 ant-design-vue@1.6.2 @formily/core@2.3.2 @formily/vue@2.3.2 ``` 如果遇到包管理器错误,请尝试清理缓存并重新安装[^4]: ```bash npm config set proxy null npm config set proxy false npm cache clean --force yarn cache clean ``` --- #### 示例代码 ##### 主文件 (`App.vue`) ```vue <template> <a-card title="筛选与表格"> <!-- 筛选区域 --> <formily-form :schema="filterSchema" /> <!-- 查询按钮 --> <div style="margin-top: 16px;"> <a-button type="primary" @click="handleSearch">查询</a-button> </div> <!-- 表格区域 --> <a-table :columns="tableColumns" :data-source="filteredData" bordered row-key="id" > <template #action="{ record }"> <span>编辑 | 删除</span> </template> </a-table> </a-card> </template> <script> import { createForm, Schema } from &#39;@formily/core&#39;; import { Form as FormilyForm } from &#39;@formily/vue&#39;; import { Input, Select, Radio } from &#39;ant-design-vue&#39;; // 创建表单实例 const form = createForm(); export default { components: { FormilyForm, AInput: Input, ASelect: Select, ARadioGroup: Radio.Group, ARadioButton: Radio.Button, }, data() { return { filterSchema: new Schema({ properties: { name: { type: &#39;string&#39;, title: &#39;名称&#39;, &#39;x-component&#39;: &#39;AInput&#39;, // 输入框 }, category: { type: &#39;string&#39;, enum: [&#39;类别一&#39;, &#39;类别二&#39;, &#39;类别三&#39;], title: &#39;分类&#39;, &#39;x-component&#39;: &#39;ASelect&#39;, // 下拉框 }, status: { type: &#39;string&#39;, enum: [ { label: &#39;启用&#39;, value: &#39;active&#39; }, { label: &#39;禁用&#39;, value: &#39;inactive&#39; } ], title: &#39;状态&#39;, &#39;x-component&#39;: &#39;ARadioGroup&#39;, // 单选按钮组 &#39;x-component-props&#39;: { buttonStyle: &#39;solid&#39; } }, }, }), tableColumns: [ { title: &#39;ID&#39;, dataIndex: &#39;id&#39;, key: &#39;id&#39; }, { title: &#39;名称&#39;, dataIndex: &#39;name&#39;, key: &#39;name&#39; }, { title: &#39;分类&#39;, dataIndex: &#39;category&#39;, key: &#39;category&#39; }, { title: &#39;操作&#39;, slots: { customRender: &#39;action&#39; } }, ], rawData: [ { id: 1, name: &#39;记录一&#39;, category: &#39;类别一&#39;, status: &#39;active&#39; }, { id: 2, name: &#39;记录二&#39;, category: &#39;类别二&#39;, status: &#39;inactive&#39; }, { id: 3, name: &#39;记录三&#39;, category: &#39;类别三&#39;, status: &#39;active&#39; }, ], }; }, computed: { filteredData() { const formData = this.form.values; let result = [...this.rawData]; if (formData.name) { result = result.filter(item => item.name.includes(formData.name)); } if (formData.category) { result = result.filter(item => item.category === formData.category); } if (formData.status) { result = result.filter(item => item.status === formData.status); } return result; }, }, methods: { handleSearch() { console.log(&#39;当前筛选条件:&#39;, this.form.values); }, }, }; </script> ``` --- ### 功能说明 1. **筛选功能** - 使用 `Formily` 构建动态表单,支持多种字段类型(如输入框、下拉框、单选按钮等),并通过绑定数据实现过滤逻辑[^1]。 2. **表格展示** - 基于 `Ant-Design-Vue` 的 `<a-table>` 组件渲染表格,并通过计算属性 `filteredData` 过滤显示的数据[^3]。 3. **交互设计** - 提供“查询”按钮触发筛选逻辑,同时保留原始数据以便重置或扩展其他功能。 --- ### 注意事项 - 如果运行过程中出现版本不兼容问题,请确认所使用的库版本是否匹配。例如,`@vitejs/plugin-vue` 需要 Vue 版本 >=3.2.13- 对于复杂场景下的性能优化,可以考虑分页加载或虚拟滚动技术来提升用户体验。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

web_Hsir

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值