[英]How can I access this.$route from within vue-apollo?
我正在使用vue-apollo
和graphql-tag
构建GraphQL查询。
如果我硬编码我想要的ID,它可以工作,但我想将当前路径ID作为变量传递给Vue Apollo。
工作 (硬编码ID):
apollo: {
Property: {
query: PropertyQuery,
loadingKey: 'loading',
variables: {
id: 'my-long-id-example'
}
}
}
但是,我无法做到这一点:
不起作用 (尝试访问此ID。路由获取ID):
apollo: {
Property: {
query: PropertyQuery,
loadingKey: 'loading',
variables: {
id: this.$route.params.id
}
}
}
我收到错误:
未捕获的TypeError:无法读取未定义的属性'params'
有没有办法做到这一点?
编辑 :完整的脚本块,以便更容易看到发生了什么:
<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>
阅读vue-apollo的文档 (参见“反应参数”部分),您可以使用this.propertyName
来使用vue反应属性。 所以只需将路径参数初始化为数据属性,然后在这样的apollo对象中使用它
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
}
}
}
}
}
虽然接受的答案对于海报的例子是正确的,但如果你使用简单的查询,它就比必要的复杂得多。
在这种情况下, this
不是组件实例,因此您无法访问this.$route
apollo: {
Property: gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`
}
但是,您只需将其替换为函数,它就会像您期望的那样工作。
apollo: {
Property () {
return gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`
}
}
无需设置额外的道具。
您不能像这样访问“this”对象:
variables: {
id: this.$route.params.id // Error here!
}
但你可以这样:
variables () {
return {
id: this.$route.params.id // Works here!
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.