1

I have a Table components which I want to make reuseable. The Table component takes in an array of objects and loops through them with the v-for directive. The Table component looks like this:

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

Then I want to reuse this in the parent component and parse the tableData is an array of objects. This works fine, but I can't find a way to access the properties. Instead I get the whole object in each td element. The parent component looks like this:

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

I've try to bind it in different ways, and know right now the "element" binding, of cause parses the entire object.

So my question is, how can I access the users.name in the parent component? I'm still kinda new to VueJS. Thank you in advance.

2 Answers 2

1

You could pass the property name as key in the headers then map your elements based on that key:

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

table component:

   <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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man! Exactly what I was looking for.
0

You can use computed properties in parent component, e.g. for Users:

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

Then use it in your component's props:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.