简体   繁体   English

Vue 3 通过变量名访问 object 属性

[英]Vue 3 access object property by variable name

I am passing this from the parent as a prop我从父母那里传递这个作为道具

table_fields: [
    {label: 'Var 1', field: 'var_1'},
    {label: 'Var 2', field: 'var_2'},
    {label: 'Var 3', field: 'var_3'},
    {label: 'Var 4', field: 'var_4'},
    {label: 'Var 5', field: 'var_5'},
],

in the child component I am doing this在子组件中我正在这样做

<table id="companiesList" class="table table-sm table-stripedd table-borderless table-hover table-responsivev">
    <thead>
        <tr>
            <th data-type="text" v-for="tableField in tableFields"  :key="tableField">{{tableField.label}}</th>
        </tr>
    </thead>
    <tbody v-if="date_loaded">
        <tr  v-for="single in data.data" :key="single.DUNS">
            <td v-for="tableField in tableFields" :key="tableField">{{single.tableField.label}}</td>
        </tr>
    </tbody>
    <tbody v-else>
        <tr>
            <td colspan="12" class="text-center">Loading...</td>
        </tr>
    </tbody>
</table>

Here I am getting data from an API call.在这里,我从 API 调用中获取数据。

The table header is as expected, but not sure how to get value from API data in the loop.表 header 符合预期,但不确定如何从循环中的 API 数据中获取值。

I tried this:我试过这个:

{{single.tableField.label}} : Cannot read property 'label' of undefined {{single.tableField.label}} :无法读取未定义的属性“标签”

{{single.{{tableField.label}}}} : Parsing error {{single.{{tableField.label}}}} :解析错误

Wat I want is to get data which is like {{single.var_1}}我想要的是获取类似于{{single.var_1}}的数据

How to achieve this?如何做到这一点? Thanks in advance提前致谢

Use bracket notation to access a variable property name of single , otherwise the code looks for a property whose name is the string tableField , which doesn't exist:使用括号表示法访问变量属性名称single ,否则代码将查找名称为字符串tableField的属性,该字符串不存在:

<td v-for="tableField in tableFields" :key="tableField.label">
  {{ single[tableField.label] }}
</td>

When using dot notation , the segments are taken as literal property names.使用点表示法时,段被视为文字属性名称。 when using bracket notation , the expression inside the brackets is evaluated for the property name.使用括号表示法时,括号内的表达式会针对属性名称进行评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM