下面的實例展示了一個簡單的基於 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>