0

Problem overview:

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.

1 Answer 1

1

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

2 Comments

Thank you! In Vue, would [header] be called a property, a member, or is the language consistent as if we're referring to JSON objects and call them values and keys?
Yes. You can add any valid javascript expression within {{ }} and it will be evaluated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.