首页 > 解决方案 > vue-apollo 组件间共享查询定义

问题描述

我刚开始使用 vue-apollo,我想知道如何优化 apollo 查询的一些使用。我有一些使用完全相同的阿波罗查询的组件。

查询本身可以在一个单独的文件中,因为它只是一个常量:

export const accountByPath = gql`
    query accountByPath($path: String!) {
        account: accountByPath(path: $path) {
            id
            name
        }
    }`
;

它可以很容易地在我的组件中使用:

<script>
    export default {
        props: ['path'],
        apollo: {
            account: {
                query: accountByPath,
                variables() {
                        return {path: this.path}
                },
                subscribeToMore: {
                    document: updateAccountSubscription,
                    variables() {
                        return {
                            path: this.path,
                        }
                    },
                }
            }
        }
    }
</script>

我不想在每个使用它的组件中重复这个定义。但是我如何移动完整的阿波罗定义呢?天真地,我首先尝试将定义提取到一个函数中,但这不起作用:

<script>
   function getQuery(path) {
        return {
            query: accountByPath,
            variables() {
                return {path: path}
            },
            subscribeToMore: {
                document: updateAccountSubscription,
                variables() {
                    return {
                        path: path,
                    }
                },
            }
        }
    };

    export default {
        props: ['path'],
        apollo: {
            account: () => getQuery(this.path)
        }
    }

</script> 

那么,如何重用相同的查询定义,包括变量和订阅?

标签: vue.jsgraphqlvue-apollo

解决方案


啊,我在问这个问题几分钟后就成功了。

<script>
   const getQuery = function accountQuery() {
        return {
            query: accountByPath,
            variables() {
                return {path: this.path}
            },
            subscribeToMore: {
                document: updateAccountSubscription,
                variables() {
                    return {
                        path: this.path,
                    }
                },
            }
        }
    };

    export default {
        props: ['path'],
        apollo: {
            account: getQuery
        }
    }

</script> 

当然,getQuery常量可以移动到不同的文件中。所以我的洞察力只是在常量函数定义中使用“this”而不是使用它作为参数


推荐阅读