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

2023-05-10 0 4,183

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>
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

1. JK下载官网所有资源来源于开发团队,加入会员即可下载使用!如有问题请联系右下角在线客服!
2. JK下载官方保障所有软件都通过人工亲测,为每位会员用户提供安全可靠的应用软件、游戏资源下载及程序开发服务。
3. JK开发团队针对会员诉求,历经多年拥有现今开发成果, 每款应用程序上线前都经过人工测试无误后提供安装使用,只为会员提供安全原创的应用。
4. PC/移动端应用下载后如遇安装使用问题请联系右下角在线客服或提交工单,一对一指导解决疑难。

JK软件下载官网 技术分享 TS+Vue3,数组元素的类型为联合类型,如何在模板v-for中判断元素的具体类型? https://www.jkxiazai.com/1720.html

JK软件应用商店是经过官方安全认证,保障正版软件平台

相关资源

官方客服团队

为您解决烦忧 - 24小时在线 专业服务