面试题答案
一键面试在Vue组件中使用TypeScript定义prop类型,有以下几种常见方法:
-
使用
PropType
辅助类型:import { defineComponent } from 'vue'; import { PropType } from 'vue'; interface User { name: string; age: number; } export default defineComponent({ name: 'MyComponent', props: { // 定义接收字符串类型且必传的prop title: { type: String as PropType<string>, required: true }, userInfo: { type: Object as PropType<User>, default: () => ({ name: '', age: 0 }) } } });
-
使用接口定义props:
import { defineComponent } from 'vue'; interface MyProps { title: string; count: number; } export default defineComponent({ name: 'MyComponent', props: ['title', 'count'] as (keyof MyProps)[], setup(props: MyProps) { // 使用props return {}; } });
-
使用
defineProps
宏(在单文件组件<script setup>
中):<script setup lang="ts"> const props = defineProps<{ title: string; isVisible: boolean; }>(); </script>
以定义一个接收字符串类型且为必传的prop为例,使用PropType
的方式如下:
import { defineComponent } from 'vue';
import { PropType } from 'vue';
export default defineComponent({
name: 'MyComponent',
props: {
message: {
type: String as PropType<string>,
required: true
}
}
});
在<script setup>
中使用defineProps
宏的方式如下:
<script setup lang="ts">
const props = defineProps<{
message: string;
}>();
</script>