Apr 24, 2025
7
Level 1
Show row number of tab in a tab
Hi there,
I use Inertia with Vue.
Here is the data input I have :
[
{
id: 20,
name: "John Doe",
books: [
{
id: 158,
title: "The Great Gatsby",
},
]
},
{
id: 32,
name: "Jane Smith",
books: [
{
id: 12,
title: "To Kill a Mockingbird",
},
{
id: 45,
title: "1984",
}
]
},
{
id: 13,
name: "Alice Johnson",
books: [
{
id: 78,
title: "Pride and Prejudice",
}
]
}
]
Here is the output I would like :
| N | Title | User |
|---|-----------------------|---------------|
| 1 | The Great Gatsby | John Doe |
| 2 | To Kill a Mockingbird | Jane Smith |
| 3 | 1984 | Jane Smith |
| 4 | Pride and Prejudice | Alice Johnson |
Here is the vue page I wrote but I have no idea how to deal with the counter at the first column :
<script setup>
defineProps({
mydata: {
type: Array,
default: () => [],
},
});
</script>
<template>
<div class="table">
<div class="table-row">
<div class="table-cell">N</div>
<div class="table-cell">Title</div>
<div class="table-cell">User</div>
</div>
<template v-for="user in mydata" :key="user.id">
<div class="table-row" v-for="book in user.books" :key="book.id">
<div class="table-cell">{{ A COUNTER OF ROW HERE }}</div>
<div class="table-cell">{{ book.title }}</div>
<div class="table-cell">{{ user.name }}</div>
</div>
</template>
</div>
</template>
I tried the script code below and called getcount() in the cell but I got the error Maximum recursive updates exceeded in component <MyComponent>
const count = ref(0);
const getCount = () => ++count.value;
Thanks for your advices !
Level 1
Finally I decided to use a computed const with a flatMap to avoid the two nested loops. This way I can use the index of the resulted list.
<script setup>
import { computed } from "vue";
const props = defineProps({
mydata: {
type: Array,
default: () => [],
},
});
const flatdata = computed(() =>
props.mydata.flatMap((user) =>
user.books.map((book) => ({
title: book.title,
name: user.name,
}))
)
);
</script>
<template>
<div class="table">
<div class="table-row">
<div class="table-cell w-10">N</div>
<div class="table-cell w-10">Title</div>
<div class="table-cell w-10">User</div>
</div>
<div class="table-row" v-for="(book, index) in flatdata" :key="book.id">
<div class="table-cell">{{ index + 1 }}</div>
<div class="table-cell">{{ book.title }}</div>
<div class="table-cell">{{ book.name }}</div>
</div>
</div>
</template>
Let me know if you have better...
Please or to participate in this conversation.