我正在使用 Vue.js 3 和 Typescript 开发单页应用程序。
该问题影响 View 和单个文件组件。 People.vue
从后端检索数据并显示在多个 PersonRow.vue
组件使用 v-for
.尽管明确定义了数据属性类型,但我在浏览器控制台中收到警告:[Vue warn]: Invalid prop: Type check failed for prop "person". Expected Person, got Object
一切正常,我可以更改 PersonRow.vue
中的属性类型至 Object
摆脱警告,但我想让类型检查正常工作。
People.vue
<template>
<div class="container">
<PersonRow v-for="person in people" :key="person.id" :person="person" />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { Person, getPeople } from '../services/person'
import PersonRow from '@/components/PersonRow.vue'
export default defineComponent({
components: {
PersonRow
},
data () {
return {
people: new Array<Person>()
}
},
mounted () {
getPeople().then(
response => {
this.people.push(...response)
})
}
})
</script>
PersonRow.vue
<template>
<div class="row">
<div class="col">{{ person.givenName }}</div>
<div class="col">{{ person.familyName }}</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { Person } from '../services/person'
export default defineComponent({
props: {
person: {
type: Person,
required: true
}
}
})
</script>
person.ts
export class Person {
constructor (id: number, givenName: string, familyName: string) {
this.id = id
this.givenName = givenName
this.familyName = familyName
}
id: number;
givenName: string;
familyName: string;
}
export async function getPeople (): Promise<Person[]> {
const response = await fetch('https://api.example.com/people')
return await response.json() as Person[]
}
最佳答案
export default defineComponent({
props: {
person: {
type: Object as PropType<Person>,
required: true
}
}
})
更深的潜水是的,docs说:另外,
type
也可以是自定义构造函数,断言将使用 instanceof
进行。查看但是为了使其工作,必须使用
new Person()
创建传递给 prop 的对象。构造函数。问题是你的 getPeople ()
函数没有创建 Person
的数组实例 - 它只是使用 json()
创建的常规 JS 对象的类型转换数组至 Person[]
.类型转换不会改变对象的运行时类型......
关于typescript - Vue.js 3 : props type validation with custom type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64325502/