Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm constructing a GraphQL query using vue-apollo and graphql-tag.

If I hardcode the ID I want, it works, but I'd like to pass the current route ID to Vue Apollo as a variable.

Does work (hardcoded ID):

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

However, I'm unable to do this:

Doesn't work (trying to access this.$route for the ID):

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

I get the error:

Uncaught TypeError: Cannot read property 'params' of undefined

Is there any way to do this?

EDIT: Full script block to make it easier to see what's going on:

<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>
like image 315
Michael Giovanni Pumo Avatar asked Jul 14 '17 10:07

Michael Giovanni Pumo


2 Answers

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!  
    }
}
like image 152
Jonas Avatar answered Nov 11 '22 03:11

Jonas


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
        }
      }
    }
  }
} 
like image 9
Vamsi Krishna Avatar answered Nov 11 '22 03:11

Vamsi Krishna