In my Vuejs
project, I am currently developing a reusable table component that looks like this:
Table Component Structure:
<template>
<div>
<table class="table">
<thead>
<tr>
<th v-for="item in headers">
{{ item }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in contents">
<th scope="row">
{{ index+1 }}
</th>
<td>
{{ item.first_name }}
</td>
<td>
{{ item.last_name }}
</td>
<td>
{{ item.username }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
name: "table-type-1",
props: ['contents', 'headers']
}
</script>
Initially, I was able to display the table data successfully by passing the following dataset as props:
data() {
return {
headers: ['#', 'First Name', 'Last Name', 'Username'],
contents: [
{ first_name: 'Jhon', last_name: 'Stone', username: '@jhon' },
{ first_name: 'Lisa', last_name: 'Nilson', username: '@lisa' },
{ first_name: 'Larry', last_name: 'the Bird', username: '@twitter' }
]
}
}
However, I realized that the table might need to accommodate different data structures in the future, such as:
data() {
return {
headers: ['#', 'Company Name', 'City', 'Turn Over (In Billions)'],
contents: [
{ company_name: 'ABC Infotech', city: 'New Jersey', turn_over: 100 },
{ company_name: 'Amazon Web Services', city: 'New York', turn_over: 400 },
{ company_name: 'Digital Ocean', city: 'Washington', turn_over: 200 }
]
}
}
To address this flexibility, I am considering passing a keys-value pair in the headers data to map keys to specific columns like this:
data() {
return {
headers: [
{ title: '#', key: index, },
{ title: 'Company Name', key: 'company_name'},
{ title: 'City', key: 'city'},
{ title: 'Turn Over (In Billions)', key: 'turn_over' }
],
contents: [
{ company_name: 'ABC Infotech', city: 'New Jersey', turn_over: 100 },
{ company_name: 'Amazon Web Services', city: 'New York', turn_over: 400 },
{ company_name: 'Digital Ocean', city: 'Washington', turn_over: 200 }
]
}
}
Alternatively, I could simply pass the key variables like this:
data() {
return {
headers: ['#', 'Company Name', 'City', 'Turn Over (In Billions)'],
keys: ['index', 'company_name', 'city', 'turn_over'],
contents: [
{ company_name: 'ABC Infotech', city: 'New Jersey', turn_over: 100 },
{ company_name: 'Amazon Web Services', city: 'New York', turn_over: 400 },
{ company_name: 'Digital Ocean', city: 'Washington', turn_over: 200 }
]
}
}
Do you have any suggestions on how I can achieve this flexibility in my table component, such as integrating these keys into the v-for element? Any advice or insights would be greatly appreciated. Thank you.