搜索组件之a-range-picker

 组件:

<template>
  <div class="searchComponent">
    <a-form
      :model="form"
      ref="formRef"
      layout="inline"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-row :gutter="12" style="width: 100%">
        <a-col
          v-for="(item, index) in searchitemList"
          :key="index"
          :xs="xs ? xs : 12"
          :sm="sm ? sm : 12"
          :md="md ? md : 12"
          :lg="lg ? lg : 12"
          :xl="xl ? xl : item.type == 'rangeDate' ? 10 : 8"
          :xxl="xxl ? xxl : item.type == 'rangeDate' ? 8 : 6"
        >
          <a-form-item
            :rules="
              item.rules
                ? [
                    ...item.rules,
                    {
                      validator: item.checkName
                        ? checkName
                        : item.type == 'rangeDate'
                        ? checkRangeDate
                        : checkNo,
                    },
                  ]
                : []
            "
            :name="item.queryName"
          >
            <template #label>
              <span>{{ item.label }}</span>
            </template>
            <a-input
              v-if="item.type == 'input'"
              v-model:value="form[item.queryName]"
              :placeholder="item.placeholder"
            ></a-input>
            <Select
              ref="selectRequest"
              v-if="item.type == 'scrollSelect'"
              :watchParams="item.watchParams"
              :isRequiredParams="item.isRequiredParams"
              :params="item.requestParams ? item.requestParams : {}"
              :objectName="`${item.queryName}`"
              :isAffect="item.isAffect"
              :value="item.val"
              :allowClear="item.requestAllowClear"
              :popupScroll="item.scrollFunc"
              @selectedValue="(value) => selectedValue(value, item.isAffect)"
            />
            <a-select
              @change="(val) => changeSelect(`${item.queryName}`, val)"
              v-if="item.type == 'select'"
              :allowClear="item.allowClear"
              v-model:value="form[item.queryName]"
              :placeholder="item.placeholder"
            >
              <a-select-option
                v-for="selectItem in item.selectList"
                :key="selectItem.value"
                :value="selectItem.value"
                >{{ selectItem.name }}</a-select-option
              >
            </a-select>
            <a-range-picker
              v-model:value="form[item.queryName]"
              v-if="item.type == 'rangeDate'"
              :picker="item.picker"
              show-time="false"
              :format="item.format"
          valueFormat="YYYY-MM-DDTHH:mm:ssZ"
            ></a-range-picker>
          </a-form-item>
        </a-col>
        <a-col :md="12" :lg="12" :xl="6" :xxl="4">
          <a-button @click="onSubmit" type="primary">查询</a-button>
          <a-button style="margin-left: 8px" @click="resetEvent">重置</a-button>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, watch, getCurrentInstance, nextTick } from "vue";
import zhCN from "ant-design-vue/es/locale/zh_CN";
import Select from "@/components/Select/index.vue";
import moment from "moment";
import type { Dayjs } from 'dayjs';
type RangeValue = [Dayjs, Dayjs];
import { message } from "ant-design-vue";
const emit = defineEmits();
const props = defineProps({
  xs: { type: Number },
  sm: { type: Number },
  md: { type: Number },
  lg: { type: Number },
  xl: { type: Number },
  xxl: { type: Number },
  labelCol: { type: Object, default: { span: 7 } },
  wrapperCol: { type: Object, default: { span: 17 } },
  searchitem: {
    type: Array,
    default: () => {
      return [
        {
          type: "", // 搜索条件类型 input,select,rangeDate,scrollSelect
          label: "", // 搜索条件名称
          val: null, // 值
          rules: [], // 校验规则
          selectList: [], // 下拉框选项
          placeholder: "", // 占位符提示
          queryName: "", // 字段名称
          allowClear: null, // 下拉框是否允许删除选项
          scrollFunc: () => {}, // 'scrollSelect'时,请求接口
          requestAllowClear: false, // 'scrollSelect'时,是否允许清除
          watchParams: true, // 'scrollSelect'时,是否请求的监听参数
          requestParams: {}, // 'scrollSelect'时,请求接口参数
          isAffect: true, // 'scrollSelect'时,选值时是否影响其他scrollSelect的选择
        },
      ];
    },
  },
  // 查询方法
  submitFunc: {
    type: Function,
    default: null,
  },
  // 被影响的选择器的事件
  selectFormFunc: {
    type: Function,
    default: () => {},
  },
  // 被控制/被影响的其他请求下拉框
  controlSelect: {
    type: Function,
    default: () => {},
  },
});
// 搜索表单数组
const searchitemList = ref([]);
// 表单的ref
const formRef = ref();
// 表单
let form = reactive({});
// 查询
function onSubmit() {
  formRef.value
    .validate()
    .then((res) => {
      props.submitFunc(form);
    })
    .catch((err) => {
      // message.warn('请检查搜索内容')
    });
}
// 请求下拉框的ref
const selectRequest = ref(null);
// 重置
function resetEvent() {
  formRef.value.resetFields();
  // 请求下拉中的值清空
  if (selectRequest.value && selectRequest.value.length > 0) {
    selectRequest.value.forEach((item) => {
      item.delSelectedData();
    });
  }
}
// select组件调用的方法(params子组件中传递的值,isAffect是否影响其他请求下拉框)
function selectedValue(params, isAffect) {
  form[params.key] = params.value;
  if (isAffect) {
    // 请求下拉框选中数据改变其他请求下拉框
    props.controlSelect(form);
    if (selectRequest.value[1]) {
      selectRequest.value[1].delSelectedData();
    }
  }
}
// select中的值改变,1.表单赋值,2.如果有被影响的数据,调用父组件中传递的方法
function changeSelect(params, value) {
  form[params] = value;
  props.selectFormFunc(form[params], form);
}
// 日期校验
async function checkRangeDate(_rule, val) {
  const startDate = new Date(val[0]).valueOf();
  const endDate = new Date(val[1]).valueOf();
  const day = 365 * 24 * 3600 * 1000; // 31536000000
  if (endDate - startDate > day) {
    return Promise.reject("选择日期不能超过365天");
  } else {
    return Promise.resolve();
  }
}
// 不校验
async function checkNo() {
  return Promise.resolve();
}
function resetRangeDate() {
  formRef.value.clearValidate("time");
}
const currentInstance = getCurrentInstance();
defineExpose({
  onSubmit,
  resetRangeDate,
});
watch(
  () => props.searchitem,
  (newVal, oldVal) => {
    if (newVal) {
      searchitemList.value = newVal;
      searchitemList.value.forEach((item) => {
        form[item.queryName] = item.val;
      });
    }
  },
  { deep: true, immediate: true }
);
</script>
<style lang="less" scoped>
.searchComponent {
  background-color: #fff;
  padding: 24px 24px 40px;
  // margin-bottom: 20px;
}
.ant-form-item {
  margin-bottom: 24px;
}
.labelSelect {
  width: auto !important;
  :deep(.ant-select-selection) {
    border: none !important;
    box-shadow: none !important;
  }
  :deep(.ant-select-selection:hover) {
    border: none !important;
    box-shadow: none !important;
  }
}
.switchBtn {
  display: flex;
  cursor: pointer;
  .anticon {
    margin-top: 4px;
    color: #1890ff;
  }
}
</style>

页面使用:

  <SearchItem
          :searchitem="searchitem"
          :submitFunc="submitFunc"
        ></SearchItem>
const searchitem = [
    {
        type: "input",
        label: "API ID",
        val: "",
        placeholder: "API ID",
        queryName: "ApiTemplateId",
    },
    {
        type: "input",
        label: "API版本Id",
        val: "",
        placeholder: "API版本Id",
        queryName: "ApiTemplateVersionId",
    },
    {
        type: "select",
        label: "记录类型",
        val: 1,
        allowClear: true,
        placeholder: "",
        queryName: "IsSuccess",
        selectList: [
          { value: 1, name: "成功" },
          { value: 0, name: "失败" },
        ],
      },
      {
        type: "rangeDate",
        label: "创建时间",
        format:"YYYY-MM-DD HH:mm:ss",
        val: "",
        placeholder: "创建时间",
        queryName: "time",
    },
    
];
function submitFunc(form) {
    searchParam.value = {
      Start_CreationTime:form.time[0]?moment(form.time[0]).format("YYYY-MM-DD HH:mm:ss"):'',
      End_CreationTime:form.time[1]?moment(form.time[1]).format("YYYY-MM-DD HH:mm:ss"):'',
    ApiTemplateId : form.ApiTemplateId,
    ApiTemplateVersionId : form.ApiTemplateVersionId,
     IsSuccess : form.IsSuccess === 0?false:true
  };
  if(form.IsSuccess==0){
    columns.value.splice(3, 0, {
         title: "异常信息",
         dataIndex: "errorMessage",
         ellipsis: true,
         show:false
     });
     apidividerbutton1.value=napidividerbutton
      apioperatingButton1.value=napioperatingButton
  }
  else{
     apidividerbutton1.value=apidividerbutton
      apioperatingButton1.value=apioperatingButton
        const hasError = columns.value.some(item => item.dataIndex === 'errorMessage');
    if(hasError){
const newArr = columns.value.filter(item => item.dataIndex !== 'errorMessage');
columns.value=newArr
    }
  }
    getData();
}