在子组件 VueJS 中循环遍历对象时将对象解析为道具

Parsing objects as props while looping through them in child component VueJS

我有一个 Table 组件,我想使其可重用。 Table 组件接收一个对象数组并使用 v-for 指令循环遍历它们。 Table 组件如下所示:

<template>
    <table>

      <thead>
       <tr>
        <th v-for="header in tableHeaders">{{ header }}</th>
       </tr>
      </thead>

      <tbody>
       <tr v-for="elements in tableData">
        <td>{{ elements }}</td>
       </tr>
      </tbody>

    </table>
</template>

<script>

export default {
  name: "Table",
  props: {
    tableData: Array,
    tableHeaders: Array,
    header: String
  },
}
</script>

那我想在父组件中复用这个,解析tableData是一个对象数组。这工作正常,但我找不到访问属性的方法。相反,我在每个 td 元素中得到了整个对象。父组件如下所示:

<template>
    <Table title="All users in the community" :table-data="users" :table-headers="headers"/> 
</template>


<script>
import Table from "@/components/Table";

export default {
  components: {
    Table
  },
  data() {
    return {
      users: [{name: "firstName", email: "firstEmail"}, {name: "secoundName", email: "secoundEmail"}], 
      headers: ["Name", "Email"],
    };
  },
};
</script>

我尝试以不同的方式绑定它,现在知道“元素”绑定,当然会解析整个对象。

所以我的问题是,如何访问父组件中的 users.name?我对 VueJS 还是有点陌生​​。提前谢谢你。

您可以将 属性 名称作为键传递给 headers,然后根据该键映射您的元素:

headers: [{label:"Name",key:"name"},{label: "Email",key:"email"}],

table 分量:

   <table>

      <thead>
       <tr>
        <th v-for="header in tableHeaders">{{ header.label }}</th>
       </tr>
      </thead>

      <tbody>
       <tr v-for="elements in tableData">
        <td v-for="header in tableHeaders">{{elements[header.key]}}</td>
       </tr>
      </tbody>

    </table>

您可以在父组件中使用计算属性,例如对于用户:

computed: {
  tableUsers() {
    return this.users.map(user => user.name);
  }
}

然后在组件的道具中使用它:

<Table title="All users in the community" :table-data="tableUsers" :table-headers="headers"/>