I am currently working on a Vue.js 3 and Typescript single page application project.
The issue I am facing involves a view and a single file component. In the People.vue
component, data is fetched from the backend and displayed in multiple instances of the PersonRow.vue
component using v-for
. Even though the types of data properties are explicitly defined, a warning appears in the browser console:
[Vue warn]: Invalid prop: Type check failed for prop "person". Expected Person, got Object
While everything seems to be functioning correctly, I could resolve the warning by changing the property type in PersonRow.vue
to Object
, but I prefer to have the type checks working accurately.
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[]
}