Javascript 我如何从vue apollo内访问此.$路线?
我正在使用Javascript 我如何从vue apollo内访问此.$路线?,javascript,vue.js,graphql,vue-apollo,Javascript,Vue.js,Graphql,Vue Apollo,我正在使用vue apollo和GraphQL标记构建一个GraphQL查询 如果我硬编码我想要的ID,它可以工作,但我想将当前路由ID作为变量传递给Vue Apollo 有效(硬编码ID): 但是,我无法做到这一点: 不起作用(尝试访问此ID的$route): 我得到一个错误: 未捕获的TypeError:无法读取未定义的属性“params” 有没有办法做到这一点 编辑:完整的脚本块,以便更轻松地查看正在发生的事情: <script> import gql from 'graphq
vue apollo
和GraphQL标记构建一个GraphQL查询
如果我硬编码我想要的ID,它可以工作,但我想将当前路由ID作为变量传递给Vue Apollo
有效(硬编码ID):
但是,我无法做到这一点:
不起作用(尝试访问此ID的$route):
我得到一个错误:
未捕获的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>
从“graphql标记”导入gql
const PropertyQuery=gql`
查询属性($id:id!){
属性(id:$id){
身份证件
鼻涕虫
标题
描述
价格
地区
可获得的
形象
创建数据
使用者{
身份证件
名字
姓氏
}
}
}
`
导出默认值{
名称:'属性',
数据(){
返回{
标题:“财产”,
属性:{}
}
},
阿波罗:{
财产:{
查询:PropertyQuery,
loadingKey:“正在加载”,
变量:{
id:this.$route.params.id//此处出错!
}
}
}
}
阅读vue apollo的(请参见“反应参数”部分),您可以通过使用此.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!
}
}
@瓦姆西克里希纳感谢您的回复。它是位于默认导出上的对象。我已经更新了我的问题以在上下文中显示这一点。是的,这很有效!非常感谢。因此,变量变成了一个返回对象的函数,而不是直接作为对象本身。谢谢@MichaelGiovanniPumo很乐意帮忙,坦率地说,我读了这些文件,学到了一些新东西,所以也感谢你:)
variables: {
id: this.$route.params.id // Error here!
}
variables () {
return {
id: this.$route.params.id // Works here!
}
}