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>