简体   繁体   English

如何在 Vue.js 中使用 v-for 运行方法?

[英]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".我想计算对象“a”和“d”中包含多少个sub_sub元素。 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 item.sub.reduce 不是函数

Could anyone please advise me how to fix this errors?谁能告诉我如何解决这个错误?

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>
 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM