【问题标题】:How to run a method using v-for in Vue.js?如何在 Vue.js 中使用 v-for 运行方法?
【发布时间】:2021-02-12 11:24:04
【问题描述】:

我想获得以下数据的以下输出。

・3
・1

和样本数据:

    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" },
                ]
            }
        ]
    },
]

我想计算sub_sub 中有多少元素包含在对象“a”和“d”中。 所以,我做了以下代码。

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

我运行了我的代码并在控制台中遇到了错误

  

 item.sub.reduce 不是函数

谁能告诉我如何解决这个错误?

【问题讨论】:

    标签: javascript typescript vue.js vuetify.js


    【解决方案1】:

    模板中的方法用作事件处理程序而不是用于渲染,请尝试在计算属性中使用该方法,然后使用该属性来渲染您的项目:

    @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;
      }
    }
    

    模板:

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

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 2019-06-07
      • 2018-01-21
      • 2021-05-17
      • 1970-01-01
      • 2017-03-23
      • 2019-05-07
      • 2020-07-18
      • 2019-12-25
      相关资源
      最近更新 更多