vue3 父组件如何向子组件传递泛型?
子组件:封装好的timePicker组件,
父组件A: 大数据查询,因为存储在es里,接口参数要求时间类型是 number[]
父组件B: 系统日志查询,因为存储普通数据库,接口参数要求时间类型为 string[]
实例:
子组件
<template>  <a-range-picker
    v-model:value="myvalue"
    format="YYYY-MM-DD HH:mm:ss"
    :value-format="format"
    :default-value="[dayjs().startOf('day'), dayjs()]"
    @change="handleChange"
  />
</template>
<script setup lang="ts">
import { ref } from 'vue';
import dayjs from 'dayjs';
type DateType = (Date | string | number | dayjs.Dayjs)[];
interface Prop {
  format?: string;
  range?: boolean;
}
withDefaults(defineProps<Prop>(), {
  format: 'YYYY-MM-DD HH:mm:ss',
  range: false,
});
const myvalue = ref<DateType>([dayjs().startOf('day'), dayjs()]);
const emits = defineEmits<{
  (e: 'emitchange', value: DateType): void;
}>();
function handleChange(val: DateType) {
  emits('emitchange', val);
}
</script>
父组件A:
<template> <my-date-picker
     :format="'X'"
     @emitchange="handleDateChange"
 />
</template>
<script lang="ts" setup>
import dayjs from 'dayjs';
// 接口查询  日期必须是 number
type DateType = number[];
const dateParams = ref<DateType>([
  dayjs().startOf('day').unix(),
  dayjs().unix(),
]);
function handleDateChange(val: DateType) {
  dateParams.value = val;
}
</script>
父组件B:
<template> <my-date-picker
     @emitchange="handleDateChange"
 />
</template>
<script lang="ts" setup>
import dayjs from 'dayjs';
// 接口查询  日期必须是 string
type DateType = string[];
const dateParams = ref<DateType>([
  dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
  dayjs().format('YYYY-MM-DD HH:mm:ss'),
]);
function handleDateChange(val: DateType) {
  dateParams.value = val;
}
</script>
在 A 中,format 值为 ‘X’  那么子组件的val默认为unix,也就是number
在 B 中,format 无值,那么子组件的val默认值为'YYYY-MM-DD HH:mm:ss',也就是string
报错信息为
`(property) 'emitchange': (value: DateType) => void
不能将类型“(val: DateType) => void”分配给类型“(value: DateType) => void”。
  参数“val”和“value” 的类型不兼容。ts(2322)`
回答:
template 这种写法 父组件 都没法识别子组件的Props 类型 怎么还想传递泛型
TSX 可以传递泛型

回答:
vue3 父组件给子组件传递泛型
可以看下这篇文章,可能会解决你的问题。
以上是 vue3 父组件如何向子组件传递泛型? 的全部内容, 来源链接: utcz.com/p/937299.html








