下面的实例展示了一个简单的基于 typescript 的 vue3 组件,包含了自定义类型的 props 如何处理.
前提:
-
使用 vue3 + typescript
-
tsconfig.json 的 include 包含要用到的类型定义文件,此处特指下文中的YOUR_TYPE
-
使用相对路径找到类型定义文件YOUR_TYPE,其对应的文件名应该是 YOUR_TYPE.d.ts
上级组件:
<template>
<YourComponentName
:confArr="YourCustomTypeArr"
@changeAbc="changeAbc"
/>
</template>
<script lang="ts" setup >
const changeAbc = (value: string) => {
console.log(">>> changeAbc: ", value)
}
</script>
子组件
<template>
</template>
<script lang="ts" >
import { defineComponent, PropType } from 'vue'
import { ElForm } from 'element-plus'
import { YourType } from '../PathToYourTypeDir/YOUR_TYPE'//这里使用相对路径
export default defineComponent({
name: 'YourComponentName',
components: {
ElForm,
},
props: {
confArr: {
type: Array as PropType<YourType[]>,
required: true,
},
},
emits: ['changeAbc'],
setup(props, { emit }) {
const changeAbc = (value: string) => {
emit('changeAbc', value)
}
return {
changeAbc,
}
},
})
</script>