drunkdolphin
drunkdolphin

Reputation: 797

How to run a method using v-for in Vue.js?

I want to get the following output for the following data.

・3
・1

and sample data :

    export const dummyData = [
    {
        id: "1",
        name: "a",
        sub: [
            {
                id: "1#1",
                name: "b",
                sub_sub: [
                    { id: "1#1#1", name: "b-a" },
                    { id: "1#1#2", name: "b-b" },
                ]
            },
            {
                id: "1#2",
                name: "c",
                sub_sub: [
                    { id: "1#2#1", name: "c-a" },
                ]
            },
        ]
    },
    {
        id: "2",
        name: "d",
        sub: [
            {
                id: "2#1",
                name: "e",
                sub_sub: [
                    { id: "1#2#1", name: "e-a" },
                ]
            }
        ]
    },
]

I want to count how many elements of sub_sub are includes in object "a" and "d". So, I made the following code.

    <template>
  <div>
    <ul>
        <li v-for="item in items" :key="item.i">{{rowSpanCalc(item.id)}}</li>
    </ul>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'
import { dummyData } from '~/store/dummy'

@Component({})
export default class extends Vue {
  items: any = []

  created() {
    this.items = dummyData
  }

  rowSpanCalc(item: any) {
    const count = item.sub.reduce(
      (total: any, curr: any) => total + curr.sub_sub.length,
      0
    )
    return count;
  }
}
</script>

I ran my code and got an error in console like

  

  item.sub.reduce is not a function

Could anyone please advise me how to fix this errors?

Upvotes: 1

Views: 496

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Methods in the template are used as events handler not for rendering, try to use that method inside a computed property then use that property for render your items :

@Component({})
export default class extends Vue {
  items: any = []

  created() {
    this.items = dummyData
  }

  get customItems(){
   return this.items.map(item=>({...item,count:this.rowSpanCalc(item.id)}))
  }

  rowSpanCalc(item: any) {
    const count = item.sub.reduce(
      (total: any, curr: any) => total + curr.sub_sub.length,
      0
    )
    return count;
  }
}

template :

 ...
   <li v-for="item in customItems" :key="item.id">{{item.count}}</li>
 ...

Upvotes: 3

Related Questions