Vue.js 3:自定义类型的道具类型验证

Vue.js 3: props type validation with custom type

我正在使用 Vue.js 3 和 Typescript 开发单页应用程序。

该问题影响视图和单个文件组件。 People.vue 从后端检索数据并使用 v-for 在多个 PersonRow.vue 组件中显示它。尽管明确定义了数据 属性 类型,但我在浏览器控制台中收到警告:
[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[]
}

“人”不是一种类型。类型可以是数组、对象、字符串、数字、布尔值、函数。所以类型检查工作正常。

Annotating Props

export default defineComponent({
  props: {
    person: {
      type: Object as PropType<Person>,
      required: true
    }
  }
})

深入研究

是的,docs 说:此外,type 也可以是自定义构造函数,断言将通过 instanceof 检查

但为了使其正常工作,传递给 prop 的对象必须使用 new Person() 构造函数创建。问题是你的 getPeople () 函数没有创建 Person 实例的数组——它只是类型转换用 json()Person[] 创建的常规 JS 对象的数组。类型转换不改变对象的运行时类型...