【问题标题】:Computed property on Nuxtjs and Axios?Nuxtjs 和 Axios 上的计算属性?
【发布时间】:2019-08-24 08:36:31
【问题描述】:

我想按名称返回一组唯一卡片。我可以使用以下代码在 Vuejs 中做到这一点。

<template>
  <div id='Home'>

    <div class="columns is-multiline">
        <card v-for="card in uniqueCards" :card="card" :key="card.id"/>
    </div>

  </div>
</template>

<script>
import uniqBy from 'lodash/uniqBy'
import Card from '@/components/Site/Card'

export default {
  name: 'Home',
  components: { Card },
  computed: {
    cards () {
      return this.$store.state.cards
    },
    uniqueCards () {
      return uniqBy(this.$store.state.cards, function (r) {
        return r.project
      })
    }
  }
}
</script>

我正在将我的项目转换为 Nuxtjs 并使用 api 来获取 appCards。如何使用 axios 实现与上述相同的功能?下面的作品,但我想使用 uniqueCards() 功能。我在这里做错了什么?

<template>    
    <div id="Home">

        <div class="columns is-multiline">
        <card v-for="card in appCards" :card="card" :key="card.id"/>
        </div>

    </div>
</template>

<script>
import uniqBy from 'lodash/uniqBy'
import Card from "~/components/Card.vue";

export default {
    components: {
        Card
    },
    data() {
        return {
            appCards: []
        };
    },
    async asyncData({ $axios, params }) {
        try {
            let appCards = await $axios.$get(`/appcards/`);
            return { appCards };
        } catch (e) {
            return { appCards: [] };
        }
    },
    mounted: {
        uniqueCards () {
            uniqBy(this.appCards, function (r) {
                return r.project;
        })
        }
    },
};
</script>

【问题讨论】:

  • 什么问题?
  • 我不确定如何将appCards 数据传递给函数uniqueCards() 并将其挂载到card 组件上?

标签: javascript vue.js axios nuxt.js


【解决方案1】:

没关系,让它工作!我忘记了正确的语法。

<template>    
    <div id="Home">

      <section class="section is-small">
        <div class="container">
          <div class="columns is-multiline">
            <card v-for="card in uniqueCards" :card="card" :key="card.id"/>
          </div>
        </div>
      </section>

    </div>

</template>

<script>
import uniqBy from 'lodash/uniqBy'
import Card from "~/components/Card.vue";

export default {
  components: {
    Card
  },
  data() {
    return {
      appCards: []
    };
  },
  async asyncData({ $axios, params }) {
    try {
      let appCards = await $axios.$get(`/appcards/`);
      return { appCards }
    } catch (e) {
      return { appCards: [] };
    }
  },
  computed: {
    uniqueCards: function () {
        return uniqBy(this.appCards, function (r) {
            return r.project
      })
    }
  }
};
</script>

【讨论】:

  • 即使您回答了自己的问题,您仍应说明问题所在以及解决问题的解决方案。
最近更新 更多