vue.js - 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>
那么,如何重用相同的查询定义,包括变量和订阅?
解决方案
啊,我在问这个问题几分钟后就成功了。
<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”而不是使用它作为参数
推荐阅读
- spacy - spacy 模型不将街道名称识别为实体
- angular - [karma-server]:TypeError:无法读取未定义的属性“范围”-CI 环境中的 Angular 单元测试
- sql-server - 为 SQL Server 版本 8.00.760 模拟 sql Server ROW_COUNT()
- docker - 以线程安全的方式运行多个 docker 容器实例
- c# - T-SQL insert into 有时无法随机添加到表中
- javascript - 在自定义钩子中使用钩子时触发的钩子错误使用无效?
- c - 如何将字符串与子字符串进行比较以将第一个和第二个之间的相等部分转换为'*'而不使用
- node.js - 仅在一台服务器上测试 discord bot discordjs
- eclipse - 为什么我不能将本地 GitHub 存储库添加到 Eclipse 中?
- mongodb - MongoDB Atlas 未出现在 Azure 数据工厂 2 的链接服务列表中