TS+Vue3,数组元素的类型为联合类型,如何在模板v-for中判断元素的具体类型?

新手上路,请多包涵

actions的类型为
actions: (MyButton | {slot: string})[]
MyButton接口中不包含slot属性
在如下代码中:

<div v-for="act in actions">
    <slot v-if="act.slot" :name="act.slot"/>
    <e-button v-else v-bind="act"/>
</div>

由于MyButton和{slot: string}不包含共同的属性slot,所以模板中的btn.slot将会报错,这种情况该如何处理?

阅读 2.4k
1 个回答
// src/components/MyComponent.vue

<template>
  <div v-for="(act, index) in actions" :key="index">
    <slot v-if="isSlotType(act)" :name="act.slot" />
    <e-button v-else v-bind="act" />
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

interface MyButton {
  // MyButton 接口定义
}

export default defineComponent({
  props: {
    actions: {
      type: Array as () => (MyButton | { slot: string })[],
      required: true,
    },
  },
  methods: {
    isSlotType(act: MyButton | { slot: string }): boolean {
      return "slot" in act;
    },
  },
});
</script>
推荐问题
logo
Microsoft
子站问答
访问
宣传栏