javascript - 如何使用 defineprop 和接口(interface)在 Vue 3 脚本设置中使用动态 Prop 类型

标签 javascript typescript vue.js vuejs3 vue-script-setup

我正在创建一个组件,它接收一组数据(使用基于接口(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/

相关文章:

javascript - 在新页面上链接 href 和调用函数

javascript - 如何修复 Windows 终端中的 'find' 命令

javascript - 在 JS 中构建计算器的问题

javascript - 如何解释映射到对象类型文字的接口(interface)字符串属性周围的括号?

javascript - 如何修复 Angular 中未定义的形式错误 'validate'

javascript - 如何在 Vue Js 中使用 swiper 断点

vue-component - 使用相同的形式进行创建和读取操作

javascript - 在 Angular 6 上将 html 模板包含到另一个模板中

javascript - 解析 vue 组件中的输入属性

typescript - Angular2 - 使用服务在组件之间共享数据