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

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


You can't have access to "this" object like that:

variables: {  id: this.$route.params.id // Error here! }

But you can like this:

variables () {       return {         id: this.$route.params.id // Works here!      }}


Readimg the documentation( see Reactive parameters section) of vue-apollo you can use vue reactive properties by using this.propertyName. So just initialize the route params to a data property as then use it in you apollo object like this

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        }      }    }  }} 


While the accepted answer is correct for the poster's example, it's more complex than necessary if you're using simple queries.

In this case, this is not the component instance, so you can't access this.$route

apollo: {  Property: gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`}

However, you can simply replace it with a function, and it will work as you might expect.

apollo: {  Property () {    return gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`  }}

No need for setting extra props.