You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3+TypeScript如何将枚举作为组件Prop属性传递与校验

解决方案

两个问题的核心原因分别是:

  1. Vue3 Options API 模板默认仅能访问组件实例上暴露的属性,直接在<script>中导入的枚举没有挂载到实例,因此编辑器识别不到模板中的使用,判定为未使用。
  2. Vue的prop的type字段是运行时校验参数,需要传入JS原生构造函数,而TS枚举是类型语法,编译后为普通对象,不能直接作为type值使用,需要同时配置运行时校验和TS类型标注。

1 修复ColorDisplay.vue的Prop类型报错

导入Vue提供的PropType工具类型,同时配置运行时校验规则和TS类型标注:

<template>
  <div>
    {{ color }}
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from "vue";
import Color from "../color";

export default defineComponent({
  props: {
      color: {
          // 数字枚举对应Number构造函数,若使用字符串枚举则改为String
          type: Number as PropType<Color>,
          // 运行时校验,确保传入值属于Color枚举的有效值
          validator: (value: number) => Object.values(Color).includes(value),
          required: true
      }
  }
});
</script>

如果使用更简洁的<script setup>语法,代码可简化为:

<template>
  <div>
    {{ color }}
  </div>
</template>

<script setup lang="ts">
import { PropType } from "vue";
import Color from "../color";

defineProps({
  color: {
    type: Number as PropType<Color>,
    validator: (value: number) => Object.values(Color).includes(value),
    required: true
  }
});
</script>

2 修复Home.vue的枚举导入未使用报错

Options API写法:将枚举挂载到组件实例

把导入的枚举放到data中返回,挂载到组件实例后模板即可访问:

<template>
  <div>
    <color-display :color="Color.Red" />
    <color-display :color="Color.Blue" />
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import ColorDisplay from "../components/ColorDisplay.vue";
import Color from "../color";

export default defineComponent({
  components: {
    'color-display': ColorDisplay,
  },
  data() {
    return {
      Color
    }
  }
});
</script>

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 11:24:03