Vue3互斥Props实现:组件如何二选一接收参数组合?
Vue3 实现二选一Props组合校验(支持IDE提示)
你需要组件仅接受json+jsonParserRules或jsonUrl+jsonParserRulesUrl其中一组参数,不能同时传入,但原写法直接用联合类型字面量传入defineProps触发了报错:
[@vue/compiler-sfc] 传递给defineProps()的类型参数必须是字面量类型,或者是对接口或字面量类型的引用。
正确实现方案
通过拆分接口并组合成联合类型别名的方式,既满足Vue编译器的要求,又能让IDE自动校验参数组合:
<script setup lang="ts"> // 本地JSON参数组合接口 interface LocalJsonProps { json: Record<string, any> jsonParserRules: Record<string, any> // 禁止同时传入远程参数 jsonUrl?: never jsonParserRulesUrl?: never } // 远程JSON参数组合接口 interface RemoteJsonProps { // 禁止同时传入本地参数 json?: never jsonParserRules?: never jsonUrl: string jsonParserRulesUrl: string } // 二选一的联合类型别名 type ComponentProps = LocalJsonProps | RemoteJsonProps // 传入类型别名给defineProps const props = defineProps<ComponentProps>() </script> <template> <pre>{{ JSON.stringify(props, null, 2) }}</pre> </template>
额外:运行时参数校验(可选)
如果需要在运行时也拦截非法参数组合,可以添加如下逻辑:
import { onMounted } from 'vue' onMounted(() => { const hasLocalGroup = !!props.json && !!props.jsonParserRules const hasRemoteGroup = !!props.jsonUrl && !!props.jsonParserRulesUrl if (hasLocalGroup && hasRemoteGroup) { console.error('组件错误:不能同时传入本地JSON参数组和远程JSON参数组') } else if (!hasLocalGroup && !hasRemoteGroup) { console.error('组件错误:必须传入本地JSON参数组或远程JSON参数组中的一组') } })
为什么原写法报错?
Vue SFC编译器对defineProps的类型参数有严格要求:必须是对象字面量、接口,或者对这些类型的引用,不能直接传入联合类型的字面量定义。将联合类型抽离成类型别名后,就符合编译器的要求了。
IDE提示说明
接口中的never类型会让IDE在用户传入非法组合时(比如同时传json和jsonUrl)直接抛出类型错误,实现实时参数校验。
内容的提问来源于stack exchange,提问作者Denis Gushcha
相关产品推荐
相关产品推荐

