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将会报错,这种情况该如何处理?


回答:

// 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>

以上是 TS+Vue3,数组元素的类型为联合类型,如何在模板v-for中判断元素的具体类型? 的全部内容, 来源链接: utcz.com/p/934237.html

回到顶部