TS定义组件Props的default和required

1,291 阅读3分钟

Composition API风格代码下,Vue组件声明Props有两种方式:运行时声明TS类型声明。两者是互斥的,不能在代码中混用。

“运行时声明(runtime declaration)” ,是说当props传值有误时,主要表现为在浏览器控制台报warning错误,VSCode/Webstorm是无法提前检测的。而错误一旦发生在生产环境,势必会增加问题的复现难度、定位难度,以及修复难度。

“类型声明(type declaration)” ,由于TypeScript是静态类型语言,当props传值有误时控制台也会报错,但同时VSCode会对该代码片段标红,并提示相关错误的信息,就能帮助我们提前发现问题,对程序设计更有掌控力。

本文通过一个DataNumber组件,对props的定义方式进行说明。

运行时声明

1. defineProps()数组的配置方式

由于defineProps()是编译器宏函数,所以不需要手动import导入,可以直接使用

<script setup>
// 最简单的方式:defineProps函数传递一个或多个propsName
const props = defineProps(["position", "options", "data"]);
</script>

2. defineProps()对象的简单配置方式

<script setup>
// defineProps传递的是配置对象,propName为key,数据类型为value
defineProps({
  data: [String, Number],
  position: Object,
  options: Object,
});
</script>

3. defineProps()对象的详细配置方式

<script setup>
// propName为key,但propValue是更详细的设置,支持type/required/default/validator等属性配置
defineProps({
  data: {
    type: [String, Number],
    default: "--",
  },
  position: {
    type: Object,
    required: false,
    default: {
      top: 0,
      left: 0,
    },
  },
  options: {
    type: Object,
    required: false,
    default: {
      animate: false,
    },
  },
});
</script>

TS类型声明

Vue3中使用TypeScript,先把组件中的类型定义给出来

// 排列方向-枚举类型
enum DirectionEnum {
  horizontal = "HORIZONTAL",
  vertical = "VERTICAL",
}

// 定位信息
type Position = {
  top: string | number;
  left: string | number;
  zIndex: number;
  width?: string | number;
  height?: string | number;
};

// 详细配置信息
type DataNumberOptionsType = {
  animate?: boolean;
  thousandsCharacter?: boolean;
  direction: DirectionEnum;
  label: string;
  suffix: string;
};

// 组件最终的数据类型
interface DataNumberType {
  data: string | number;
  position?: Position;
  options?: DataNumberOptionsType;
}

这里值得注意的是,DataNumberType中的结构定义,如果不加?则是必填的,有了?相当于required=false

1. defineProps<泛型参数>()的方式

<script setup lang="ts">

// 忽略上述的类型定义声明

// 通过泛型参数的方式进行props定义
defineProps<DataNumberType>();
</script>

这种方式,好在将“运行时声明”改成TS静态的类型声明,但缺点就是没办法设置默认值。

2. withDefaults+defineProps<泛型参数>()的方式

// 忽略上述的类型定义声明

// withDefaults()也是宏函数
// 第一个参数是defineProps函数调用,第二个参数是配置默认值
withDefaults(defineProps<DataNumberType>(), {
  // 基础数据类型,直接赋值
  data: "--", 
  // 复杂数据类型,需要通过一个箭头函数return出来
  position: () => ({
    left: 0,
    top: 0,
    zIndex: 0,
  }),
  options: () => ({
    animate: true,
    thousandsCharacter: true,
    direction: DirectionEnum.horizontal,
    label: "订单",
    suffix: "笔",
  }),
});

通过withDefaults()可以进行类型声明,也可以设置是否必填,还能设置默认值。但如果需要配置props.validator校验,就没办法了。

3. PropType的方式

// PropsType需要提前引入
import { type PropType } from 'vue';

// 忽略上述一大段的类型声明

defineProps({
  data: {
    type: [String, Number],
    default: '--',
    validaor(value: string) {
      if(value === '暂无数据') {
        return false
      }
    }
  },
  position: {
    type: Object as PropType<Position>,
    required: false,
    deault: {
      left: 0,
      top: 0,
      zIndex: 0,
    }
  },
  options: {
    type: Object as PropType<DataNumberOptionsType>,
    require: true,
    default: {
      animate: false,
      thousandsCharacter: false,
      direction: "horizontal",
      label: "待入馆",
      suffix: "人",
    }
  }
});

这样既能利用TS的类型声明,又能完整的使用Props的配置功能。

但仍然不完美,类型声明代码太多了,能不能抽取到独立文件,从外部文件引入呢?

Vue官方文档给出了解释:“因为 Vue 组件是单独编译的,编译器目前不会抓取导入的文件以分析源类型。计划在未来的版本中解决这个限制。”

4. PropType+ExtractPropTypes的方式

我们先把类型声明放到DataNumber.d.ts文件,然后通过ExtractPropTypes进行导出

// ExtractPropTypes需要提前引入
import { ExtractPropTypes } from 'vue';

enum DirectionEnum {
  horizontal = 'HORIZONTAL',
  vertical = 'VERTICAL',
}

type Position = {
  top: string | number;
  left: string | number;
  zIndex: number;
  width?: string | number;
  height?: string | number;
};

type DataNumberOptionsType = {
  animate?: boolean;
  thousandsCharacter?: boolean;
  direction: DirectionEnum;
  label: string;
  suffix: string;
};

// export暴露出去
export type Position = ExtractPropTypes<typeof Position>;
export type DataNumberOptionsType = ExtractPropTypes<
  typeof DataNumberOptionsType
>;
<script setup lang="ts">
import { type PropType } from 'vue';
// 使用的时候,从类型文件引入
import { Position, DataNumberOptionsType } from './DataNumber.d'

defineProps({
  data: {
    type: [String, Number],
    default: '--',
    validaor(value: string) {
      if (value === '暂无数据') {
        return false
      }
    }
  },
  position: {
    type: Object as PropType<Position>,
    required: false,
    deault: {
      left: 0,
      top: 0,
      zIndex: 0,
    }
  },
  options: {
    type: Object as PropType<DataNumberOptionsType>,
    require: true,
    default: {
      animate: false,
      thousandsCharacter: false,
      direction: "horizontal",
      label: "待入馆",
      suffix: "人",
    }
  }
});
</script>

动态组件如何根据Props过滤v-bind绑定的属性?

如上述案例,还有个新问题:v-bind绑定config到组件上,把sidcomponent属性也绑进去了,只是转换成attribute到DOM元素上。

那怎么能动态过滤呢?只有符合组件Props的key才绑定进去,不符合的抛弃

<template>
  <component
    :is="componentMap[config.component]"
    v-bind="calcPropsBindData(config.component, config)"
  ></component>
</template>

<script>
import DataNumber from "./DataNumber.vue";

const componentMap = {
  DataNumber,
};

// 引入的DataNumber是组件类,可读取到props的定义对象
// 根据组件props的key过滤config,再返回
function calcPropsBindData(config) {
  const { component } = config;
  const { props } = componentMap[component];
  const propKeys = Object.keys(props);
  const result = {};
  propKeys.map((key) => {
    result[key] = config[key];
  });
  return result;
}
</script>

示例项目

gitee.com/lianghuilin…

参考