我如何从 vue-apollo 中访问 this.$route?

How can I access this.$route from within vue-apollo?

我正在使用 vue-apollographql-tag 构建 GraphQL 查询。

如果我硬编码我想要的 ID,它可以工作,但我想将当前路由 ID 作为变量传递给 Vue Apollo。

有效(硬编码 ID):

  apollo: {
    Property: {
      query: PropertyQuery,
      loadingKey: 'loading',
      variables: {
        id: 'my-long-id-example'
      }
    }
  }

但是,我无法执行此操作:

不起作用(尝试访问这个。ID 的 $route):

  apollo: {
    Property: {
      query: PropertyQuery,
      loadingKey: 'loading',
      variables: {
        id: this.$route.params.id
      }
    }
  }

我收到错误:

Uncaught TypeError: Cannot read property 'params' of undefined

有什么办法吗?

编辑:完整的脚本块可以更容易地看到发生了什么:

<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 的 documentation(参见反应参数部分),您可以使用 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!  
    }
}