vue3 v-for遍历defineProps或者props接收的数据时,报“xx” is of type ‘unknown‘

项目场景:

vue中使用ts,且在使用props或者defineProps进行父传子时,v-for遍历收到的数组,进行取值时,报“xx” is of type 'unknown'


问题描述


原因分析:

提示:ts进行类型推导造成的报错


解决方案一:使用接口进行类型声明

提示:使用接口进行

<script setup lang="ts">

interface ITable {
    date: String,
    name: String,
    address: String,
    phone?: Number,
}
interface IColumns {
    prop: String,
    label: String,
    type?: String,
    width?: String | Number,
}
defineProps<{ columnData: IColumns[], tableData: ITable[] }>()

</script>

解决方案二:用vue3的type PropType

提示:创建一个ts文件,放类型数据,在使用的页面进行引用           

import { defineProps, type PropType } from 'vue'
import type { TypeColumn } from './index'   // PS:这里引入要写前面type
 
const props = defineProps({
    tableData: {
        type: Array,
        default: () => [],
        require: true
    },
    columnData: {
    type: Array as unknown as PropType<[TypeColumn]>,  // 需要先定义unknown 
    default: () => []
  }
})

 解决方案三:把接受的数据设为any类型

const props = defineProps({
    columnData:{
        type: Array<any>,
        default:() =>[],
        require: true
    }
})

总结:前两个都有一个弊端,不利于组件的封装;

第三个方便进行组件封装使用,但丢失了具体的类型推导

猜你喜欢

转载自blog.csdn.net/qq_38325751/article/details/130046786
今日推荐