Mic*_*umo 10 javascript vue.js graphql vue-apollo
我正在使用vue-apollo
和构建 GraphQL 查询graphql-tag
。
如果我对我想要的 ID 进行硬编码,它可以工作,但我想将当前路由 ID 作为变量传递给 Vue Apollo。
是否有效(硬编码 ID):
apollo: {
Property: {
query: PropertyQuery,
loadingKey: 'loading',
variables: {
id: 'my-long-id-example'
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我无法做到这一点:
不起作用(尝试访问 this.$route 以获取 ID):
apollo: {
Property: {
query: PropertyQuery,
loadingKey: 'loading',
variables: {
id: this.$route.params.id
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
未捕获的类型错误:无法读取未定义的属性“参数”
有没有办法做到这一点?
编辑:完整的脚本块,以便更容易地看到发生了什么:
<script>
import gql from 'graphql-tag'
const PropertyQuery = gql`
query Property($id: ID!) {
Property(id: $id) {
id
slug
title
description
price
area
available
image
createdAt
user {
id
firstName
lastName
}
}
}
`
export default {
name: 'Property',
data () {
return {
title: 'Property',
property: {}
}
},
apollo: {
Property: {
query: PropertyQuery,
loadingKey: 'loading',
variables: {
id: this.$route.params.id // Error here!
}
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
小智 11
你不能像这样访问“这个”对象:
variables: {
id: this.$route.params.id // Error here!
}
Run Code Online (Sandbox Code Playgroud)
但你可以喜欢这样:
variables () {
return {
id: this.$route.params.id // Works here!
}
}
Run Code Online (Sandbox Code Playgroud)
阅读vue-apollo的文档(参见 Reactive 参数部分),您可以通过使用this.propertyName
. 所以只需将路由参数初始化为数据属性,然后像这样在你的阿波罗对象中使用它
export default {
name: 'Property',
data () {
return {
title: 'Property',
property: {},
routeParam: this.$route.params.id
}
},
apollo: {
Property: {
query: PropertyQuery,
loadingKey: 'loading',
// Reactive parameters
variables() {
return{
id: this.routeParam
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
虽然所接受的答案对于发帖者的示例是正确的,但如果您使用简单的查询,则它会比必要的更复杂。
在这种情况下,this
不是组件实例,因此无法访问this.$route
apollo: {
Property: gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`
}
Run Code Online (Sandbox Code Playgroud)
但是,您可以简单地将其替换为函数,它就会按照您的预期工作。
apollo: {
Property () {
return gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`
}
}
Run Code Online (Sandbox Code Playgroud)
无需设置额外的道具。
归档时间: |
|
查看次数: |
2335 次 |
最近记录: |