[Framework7 Vuejs]使用v-for将asyn数据绑定到模板

时间:2019-02-22 03:49:46

标签: vue.js vuejs2 html-framework-7

我想通过调用api使用axios显示每个ID(1、2、3)的总视图,如下所示:

<f7-block>
<f7-col 
  :key="index" 
  v-for="(items, index) in list">
  Total views: {{countView(items.id)}}
</f7-col>

export default {
  data(){
    list: [];
    // list = [{id: 1}, {id: 2}, {id: 3}]
  },
  methods(){
    async countView(id){
      let url = 'xxx';
      let filter = {
        where: {
          quizId: id
        }
      }
      try{
        let res = await axios.get(url, filter);
        return res.data.countViews;
      } catch(error) {

      }

    }
  }
}

如何使用vue异步数据来显示视图数,而不是 {}

1 个答案:

答案 0 :(得分:1)

有一种更好的方法,为每个项目创建一个自定义组件。然后在每个自定义组件中调用countView

TotalView.vue

<template>
  <span v-if="count !== null">
   {{ count }}
  </span>
</template>
<script>
export default {
  name: 'TotalView'
  props: ['itemId'],
  data: () => ({
    count: null
  }),
  created() {
    this.countView(this.itemId)
  },
  methods: {
    async countView(id){
      let url = 'xxx';
      let filter = {
        where: {
          quizId: id
        }
      }
      try{
        let res = await axios.get(url, filter);
        this.count = res.data.countViews
      } catch(error) {

      }
    }
  }
}
</script>

并在您的组件中使用它:

<f7-block>
<f7-col 
  :key="index" 
  v-for="(items, index) in list">
  Total views: <total-view :itemId="items.id" />
</f7-col>