【问题标题】:Vuejs computed properties that depend on other, asynchronous, computed propertiesVuejs 计算属性依赖于其他异步计算属性
【发布时间】:2018-03-26 09:05:46
【问题描述】:

在我的 Vuejs 应用程序中,我需要将两个计算属性传递给一个名为 avatar 的组件:一个图像源和一个字符串。

问题是不是所有的item都有图片,当没有图片时,vuejs会抛出错误,因为它无法读取undefined的属性apples(因为album_id是未定义的)。

错误是从avatar 组件中那个冗长的src 属性引发的,如下:

<template>
    <div class="apples">
        <div id="mast" class="f3 b bb b--black-10">
            <h2 class="ttc">Apple's List</h2>
        </div>
        <div id="content">
            <li v-for="apple in apples" class="list-item">
                <avatar :src="apple[ 'album_id '][ 'apples' ][ '256' ]" :size="50" :appletype="apple.type"></avatar>
            </li>
        </div>
    </div>
</template>

<script>
    import Avatar from './Avatar.vue';
    import Apples from '@/api/apples';

    export default {
        name: 'apples',
        asyncComputed: {
            apples: {
                async get() {
                    const apples = await Apples.getAll();
                    return apples.data;
                },
                default: []
            }
        },
        components: {
            Avatar
        }
    };
</script>

在我在 html 模板中使用从 api 接收到的数据之前,我需要以某种方式处理它,但我不确定如何继续。在get() 函数中创建一个单独的图片数组似乎是错误的。

使用v-ifv-else 来检查是否有src 属性可以传递下去也显得很笨拙。

我是否创建另一个单独的计算方法来遍历我的项目列表并获取图片src(如果项目有一个)?

【问题讨论】:

  • 你能用样本数据做一个活生生的例子吗?
  • 或者如果您想将数据共享给子组件,请查看我的答案here

标签: javascript asynchronous vue.js


【解决方案1】:

我建议你需要为你的苹果酱创建吸气剂.. er.. source.. er.. src :)

<template>
    <div class="apples">
        <div id="mast" class="f3 b bb b--black-10">
            <h2 class="ttc">Apple's List</h2>
        </div>
        <div id="content">
            <li v-for="apple in apples" class="list-item">
                <avatar :src="getAvatar(apple, 256)" :size="50" :appletype="apple.type"></avatar>
            </li>
        </div>
    </div>
</template>

<script>
    import Avatar from './Avatar.vue';
    import Apples from '@/api/apples';

    export default {
        name: 'apples',
        methods: {
            getAvatar: function(obj, id) {
                   return obj.album_id.apples[ id ] | ''
            }
        },
        asyncComputed: {
            apples: {
                async get() {
                    const apples = await Apples.getAll();
                    return apples.data;
                },
                default: []
            }
        },
        components: {
            Avatar
        }
    };
</script>

这允许您使用您选择的任何参数和实现来创建优雅的回退。

【讨论】:

    猜你喜欢
    • 2020-02-05
    • 2020-05-17
    • 2018-05-30
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多