我刚开始使用vue-apollo,我想知道如何优化一些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> 那么,如何重用相同的查询定义,包括变量和订阅?
发布于 2019-10-15 21:00:02
啊,我在问完问题几分钟后就成功了。
<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“,而不是将其用作参数
https://stackoverflow.com/questions/58395077
复制相似问题