我正在创建一个组件,该组件接受一组数据(使用基于接口的类型化props ),然后传入第二个props ,该props 动态地 Select 我想要在数据对象中引用的属性.

我将Vue 3脚本设置语法与TypeScrip和fineProps一起使用.

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

我正在try 传递一个接口属性,这样我就可以动态地 Select 要在绘图的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" />

有没有更好的方法来做这件事?

推荐答案

try 使用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相关问答推荐

在时间轴完整日历中显示日期标题

使用JavaScript在ionic Web应用程序中更新.pane和.view的背景 colored颜色

使用TMS Web Core中的HTML模板中的参数调用过程

被CSS优先级所迷惑

Angular:动画不启动

当试图显示小部件时,使用者会出现JavaScript错误.

如何用拉威尔惯性Vue依赖下拉?

如何在模块层面提供服务?

如何避免页面第一次加载时由于CSS样式通过JavaScript更改而出现闪烁

变量的值在Reaction组件中的Try-Catch语句之外丢失

Puppeteer上每页的useProxy返回的不是函数/构造函数

OpenAI转录API错误请求

获取';无法解决导入和导入";slick-carousel/slick/slick-theme.css";';错误

<;img>;标记无法呈现图像

当代码另有说明时,随机放置的圆圈有时会从画布上消失

try 将Redux工具包与MUI ToggleButtonGroup组件一起使用时出错

将范围 Select 器添加到HighChart面积图

如何设置时间选取器的起始值,仅当它获得焦点时?

如果查询为空,则MongoDB将所有文档与$in匹配

我如何才能让p5.js在不使用实例模式的情况下工作?