Reputation: 649
I'm trying to learn some Vue.js, and I quickly ran into a use case I can't wrap my head around (yay!)
I'm trying to create a Vuejs table component. The looks like the following:
<template>
<div class="mytr">
<thead>
<tr>
<th v-for="header in headers" :key="header.id">
{{header}}
</th>
</tr>
</thead>
<tr v-for="todo in todos" :key="todo.id">
<td>{{todo.title}}</td>
<td>{{todo.completed}}</td>
</tr>
</div>
</template>
<script>
export default {
name: 'Tablerow',
data () {
return {
headers: ['title', 'completed'],
todos: []
}
},
mounted () {
fetch('https://jsonplaceholder.typicode.com/todos/').then(response => response.json()).then((data) => {
console.log(data)
this.todos = data
})
}
}
</script>
As you can see I'm using the api from jsonplaceholder.
The question is: can this be written with a syntax similar to the following:
<tr v-for="todo in todos" :key="todo.id">
<td v-for="header in headers" :key="header.id">
{{todo.header}}
</td>
</tr>
This would allow me to specify the columns I want to print from my data making this component more portable and usable.
Please forgive me if the question is too basic. I have o-kay pure JS background, Python/Django, and the rest is fairly low level.
Upvotes: 0
Views: 37
Reputation: 35259
Since each header
is a string, you can use bracket notation to access the property of todo
<tr v-for="todo in todos" :key="todo.id">
<td v-for="header in headers" :key="header.id">
{{todo[header]}}
</td>
</tr>
Upvotes: 1