封装a-select下拉增加复选框,支持全选和取消全选

发布时间 2023-10-30 17:23:02作者: 奔跑的哈密瓜

由于select下拉框中内容过多,使用下拉一个一个选取太过于麻烦,所以在下拉中增加全选和取消全选操作,增加复选框选择。

版本   vue3     Ant Design Vue@2.2.8

1.我们在看Ant Design Vue官网中,可以发现这个dropdownRender,它可以定义下拉框中的内容。

 2.封装vue组件

<template>
  <a-select
    v-model:value="inputValue"
    mode="tags"
    v-bind="$attrs"
    placeholder="请选择数据"
    :style="{ width: props.width ? props.width : '200px' }"
    option-label-prop="label"
  >
    <template #dropdownRender="{ menuNode: menu }">
      <div
        style="padding: 4px 8px; cursor: pointer;"
        @mousedown="(e) => e.preventDefault()"
        @click="addItem"
      >
        <a-button
          type="primary"
          style="margin-right: 10px;"
          @click="allSelectedFun"
          >全选</a-button
        >
        <a-button @click="clearFun">清空</a-button>
        <a-divider style="margin: 4px 0;" />
        <v-nodes :vnodes="menu" />
      </div>
    </template>
    <template v-for="item in props.options">
      <a-select-option :value="item.value" :label="item.label">
        <a-checkbox :checked="inputValue.includes(item.value)"></a-checkbox>
        {{ item.label }}
      </a-select-option>
    </template>
  </a-select>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
export default defineComponent({
  components: {
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
  },
});
</script>
<script lang="ts" setup>
import type { CascaderProps } from 'ant-design-vue';
import { ref } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
const props = defineProps<{
  options: any;//传入的列表,仅支持value label格式
  value: any;//外面v-model绑定的值   必须为v-model:value="绑定的值(根据需求自己定义)"
  width?: string;//设置a-select宽度
}>();
// 监听文本框输入
const inputValue = ref(props.value);
//将传入的v-model值赋值给当前a-select
watch(
  () => props.value,
  (newValue) => {
    inputValue.value = newValue;
  }
);
// 全选
const allSelectedFun = () => {
  props.options.forEach((item) => {
    let index = inputValue.value.indexOf(item.value);
    if (index == -1) {
      inputValue.value.push(item.value);
    }
  });
};
// 清空
const clearFun = () => {
    //使用splice是为了可以监听到变化
  inputValue.value.splice(0, inputValue.value.length);
};
</script>

<style lang="less" scoped></style>

3.main.ts中注册组件

import { createApp } from 'vue';
import Antd from 'ant-design-vue';
import App from './App.vue';
import router from './router';
import { createPinia } from 'pinia';
import piniaPluginPersist from 'pinia-plugin-persist';
// 引入选择组件
import AASelect from '@/components/aa-select/aa-select.vue';

// 全局组件挂载
const store = createPinia();
const app = createApp(App);
store.use(piniaPluginPersist);
 app.component('AASelect', AASelect);
app.use(router).use(Antd).use(store).mount('#app');

4.vue中使用

<AASelect 
          :width="'245px'" 
          :options="options" 
          v-model:value="selectData" 
          placeholder="请选择分析内容">
        </AASelect>

5.展示形式