項(xiàng)目場(chǎng)景:
vue中使用ts,且在使用props或者defineProps進(jìn)行父?jìng)髯訒r(shí),v-for遍歷收到的數(shù)組,進(jìn)行取值時(shí),報(bào)“xx” is of type 'unknown'
問(wèn)題描述
原因分析:
提示:ts進(jìn)行類型推導(dǎo)造成的報(bào)錯(cuò)
解決方案一:使用接口進(jìn)行類型聲明
提示:使用接口進(jìn)行
<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
提示:創(chuàng)建一個(gè)ts文件,放類型數(shù)據(jù),在使用的頁(yè)面進(jìn)行引用? ? ? ? ? ?
import { defineProps, type PropType } from 'vue'
import type { TypeColumn } from './index' // PS:這里引入要寫(xiě)前面type
const props = defineProps({
tableData: {
type: Array,
default: () => [],
require: true
},
columnData: {
type: Array as unknown as PropType<[TypeColumn]>, // 需要先定義unknown
default: () => []
}
})
?解決方案三:把接受的數(shù)據(jù)設(shè)為any類型
const props = defineProps({
columnData:{
type: Array<any>,
default:() =>[],
require: true
}
})
總結(jié):前兩個(gè)都有一個(gè)弊端,不利于組件的封裝;文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-572067.html
第三個(gè)方便進(jìn)行組件封裝使用,但丟失了具體的類型推導(dǎo)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-572067.html
到了這里,關(guān)于vue3 v-for遍歷defineProps或者props接收的數(shù)據(jù)時(shí),報(bào)“xx” is of type ‘unknown‘的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!