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
    }
})

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

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

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值