我正在创建一个组件,它接收一组数据(使用基于接口(interface)的类型化 Prop ),然后传入第二个 Prop ,该 Prop 动态选择我想在数据对象中引用的属性。
我正在使用带有 Typescript 和 defineProps 的 Vue 3 脚本设置语法。
<script setup lang="ts">
interface DataRow {
'id': number
'height': number
'strideLength': number
'distanceTravelled': number
'timestamp': Date
}
const props = defineProps<{
data: DataRow[]
xAxis: string
yAxis: string
}>
</script>
<template>
X Axis: {{ props.data[xAxis] }}
Y Axis: {{ props.data[YAxis] }}
<pre>
{{ data }}
</pre>
</template>
我正在尝试传递其中一个界面属性,以便我可以动态选择我在绘图的 x/y 轴上显示的内容。目前,我正在使用一个字符串,但由于它是未类型化的,所以我收到了 linter 错误。
const props = defineProps<{
data: DataRow[]
xAxis: string <- this should only be properties of my DataRow interface
yAxis: string <- this should only be properties of my DataRow interface
}>
<my-component
:data="[{id: 1, height: 2, strideLength: 0.5, distanceTravelled: 5, timestamp: new Date()}]"
:xAxis="timestamp"
:yAxis="height" />
有更好的方法吗?
最佳答案
尝试使用 keyof
类型运算符:
<script setup lang="ts">
interface DataRow {
'id': number
'height': number
'strideLength': number
'distanceTravelled': number
'timestamp': Date
}
const props = defineProps<{
data: DataRow[]
xAxis: keyof DataRow
yAxis: keyof DataRow
}>
</script>
<template>
X Axis: {{ props.data[xAxis] }}
Y Axis: {{ props.data[YAxis] }}
<pre>
{{ data }}
</pre>
</template>
关于javascript - 如何使用 defineprop 和接口(interface)在 Vue 3 脚本设置中使用动态 Prop 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73599477/