vue3 PropType

697 阅读1分钟

PropType是为了类型推断,让我们在使用的时候不论在ts中还是在模板中都能够获取类型的推断和自动补全等功能;

比如我们定义了一个list,默认是Arry类型;这个list只能知道是数组类型,不确定里面每一项是什么样,如果使用PropType<ColumnProps[]>,这样就变成了一个ColumnProps的数组,在使用list内的字段的时候,就有字段提示和总部全功能;

<template>
  <ul>
    <li v-for="column in columnList" :key="column.id">
      <img :src="column.avatar" alt="" />
      <h5>{{ column.title }}</h5>
      <p>{{ column.description }}</p>
      <a href="">进入专栏</a>
    </li>
  </ul>
</template><script lang="ts" setup>
import { defineProps, PropType, computed } from 'vue'
export interface ColumnProps { 
 id: number
  title: string
  avatar?: string
  description: string
}
const props = defineProps({
  list: { 
   type: Array as PropType<ColumnProps[]>,//类型推断
    required: true,
    default: () => [] // 提供一个空数组作为初始值
  }
})
const columnList = computed(() => {
  return props.list.map(item => {
    if (!item.avatar) {
      item.avatar = require('@/assets/no-permission.png')
    }
    return item
  })
})
</script>