Mr. Wilhelm
Mr. Wilhelm

Reputation: 31

How to use "v-for", for array in computed object

I am creating a website to list all of my projects. I am using Vuex and Firebase to store all my data.

I want each project to have its own "todo-list". When I create a new project, I create an array witch is my todo-list. In Firebase it looks like this: Screenshot of Firebase

Now I want to display a list of my projects. First I get my projects as a computed prop like this:

<script>
export default {

  computed: {
    projects () {
      return this.$store.getters.loadedProjects
    }
  },
  created () {
    this.$store.dispatch('loadProjects')
  },
}

</script>

I can loop through projects and display the title for each project.


My question is: how do I loop through the todo-array inside the computed prop?

<template>
  <div v-for="project in projects" :key="project.id">
    <p>{{ project.title }}</p>
    
    <!-- Looping through todos (array) in an computed prop -->
    <div v-for="(todo, index) in todos" :key="todo.id">
      <p>{{ project.todos[index].title }} </p>
      <p>{{ project.todos[index].completed }} </p>
    </div>
    
  </div>
</template>

Tried to use the computed prop inside v-for, but that does not work. Not sure if I understand the meaning of computed properties. Could I just define projects () inside data () ? and link the getter to the data?

<div v-for="todo in {{project.todos}} :key="todo.id>

Upvotes: 0

Views: 1027

Answers (1)

Joao Paulo
Joao Paulo

Reputation: 199

If the second loop is inside the first one, you could access it this way:

<template>
  <div v-for="project in projects" :key="project.id">
    <p>{{ project.title }}</p>
    
    <!-- Looping through todos (array) in an computed prop -->
    <div v-for="todo in project.todos" :key="todo.id">
      <p>{{ todo.title }} </p>
      <p>{{ todo.completed }} </p>
    </div>
    
  </div>
</template>

When you create a loop, in this case, project is a single element of the array, so project.todos is the list of todos of that specific project.

https://v2.vuejs.org/v2/guide/list.html#Mapping-an-Array-to-Elements-with-v-for

Upvotes: 1

Related Questions