Is there a way to retrieve the `this.$route` data while using vue-apollo?

Currently working on building a GraphQL query with vue-apollo and graphql-tag.

When I manually set the ID, everything runs smoothly. However, I'm aiming to dynamically pass the current route's ID as a variable to Vue Apollo.

Successful Implementation (using hardcoded ID):

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

Yet, attempting to access this.$route for the ID results in:

Unsuccessful Attempt (trying to retrieve ID from this.$route):

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

The error displayed is:

Uncaught TypeError: Cannot read property 'params' of undefined

Is there a workaround for achieving this functionality?

EDIT: Complete script block provided below for better context:

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

Answer №1

You won't be able to retrieve the "this" object in this manner:

variables: {
  id: this.$route.params.id // This will cause an error! 
}

However, you can do it this way:

variables () {   
    return {
         id: this.$route.params.id // This will work just fine!  
    }
}

Answer №2

When you refer to the documentation (specifically in the Reactive Parameters section) of vue-apollo, you will learn that you can utilize Vue reactive properties by simply using this.propertyName. To implement this, initialize the route parameters to a data property and then use it in your apollo object as shown below:

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

Answer №3

Although the provided answer is accurate for the specific example given by the poster, it may be unnecessarily complex when dealing with simple queries.

In this particular scenario, this does not refer to the component instance, making it impossible to access this.$route

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

However, you can easily replace it with a function and achieve the desired functionality.

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

No need to introduce additional props.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way for me to keep an image stationary on the page while allowing overlaying text to move?

Currently, I am exploring the process of coding a website that mimics the style of this particular webpage: . I am particularly interested in learning how to create a scrolling effect for text within a fixed area, while keeping the accompanying images st ...

Performing an Ajax request to the server and then sending the retrieved data back to Charts.js

After extensively researching ajax, php, and related topics, I'm facing a challenge. I want to take an array retrieved from my database and integrate it into a chart.js script. The data retrieval seems fine as per Firebug inspection, but the issue ari ...

Initiate an AJAX call

Hey there, I have a piece of code that I need some help with. <button onclick="sbt()" name="step1[save]" type="submit" class="btn-type5 next-btn-form pie" value="Далее">Send</button> function sbt(){ var phone = document.getElementById(&ap ...

"Want to know the best way to retrieve the most recent form input value using jQuery or Javascript

I've been reading a lot about using jQuery to set and get field values, but I'm encountering an issue where I can't retrieve the value after submitting, editing it in an input field, and then submitting again. It works the first time, but no ...

What is the best approach to defining a type for a subclass (such as React.Component) in typescript?

Can someone help me with writing a type definition for react-highlight (class Highlightable)? I want to extend Highlightable and add custom functionality. The original Highlightable JS-class is a subclass of React.Component, so all the methods of React.Com ...

Error occurs in ReactJS App when the state is updated in Redux only after dispatching the same action twice

Check out the following code snippet: ChartActions.js import * as types from './ChartTypes.js'; export function chartData(check){ return { type: types.CHART_DATA,check }; } ChartTypes.js export const CHART_DATA = 'CHART_DATA ...

Modifying npm packages within a web application

I have a web application where I recently installed an npm package. However, I've realized that I need to customize it by adding some code. My attempt to modify the package directly in node_modules hasn't resulted in any visible changes. Is there ...

React Scroll and Material-UI button active link not functioning correctly

Whenever the link goes to the correct page, I want to add a special background effect or change the font color. Despite trying to use CSS for this purpose, it didn't work as intended. If you want to take a look at my code on codesandbox, follow this ...

Is the `document.documentElement` consistently defined and always representing the HTML element?

I am looking to make changes to the <html> element using a script within the <head> section of an HTML page. My goal is to only access and modify the <html> element itself, without affecting any of its children. Should I wait for the DOM ...

add the elements of an array to multiple div elements sequentially

I'm attempting to update all titles in .item with the values from array. The array I am using contains the following elements: var itCats = ['one', 'two', 'three', 'four']; Additionally, this is the HTML struc ...

Refining Flask-Generated Table Content with jQuery Filters

I'm currently attempting to render a Jinja2 template that showcases an HTML table and enables dynamic filtering to search through the table content. Unfortunately, I'm facing issues with getting the search functionality to work properly. While th ...

Reveal or Conceal Information Depending on Cookie Status

Below is the Jquery code I am using: $("#tool").click(function() { $(".chelp").slideToggle(); $("wrapper").animate({ opacity: 1.0 },200).slideToggle(200, function() { $("#tool img").toggle(); }); }); When the #tool img is clicked, bot ...

Expanding and shrinking the index within a specific circular boundary in JavaScript

I'm dealing with a circular range of ASCII values from a to z, where each letter corresponds to a number between 97 and 122. I have no issue with increasing the value within this range, but I am struggling when it comes to decreasing it. For example ...

Leveraging Vue.js and TypeScript: accessing the type of the child component through refs

In my parent component, I have a child component named with a reference passed to it: <child ref="childRef" /> When trying to execute a function inside the child component from the parent component, I face some challenges: mounted() { ...

Using a personalized function in JQuery

I need to execute a JavaScript function I created after a JQuery event has been triggered. The function in question is called scrambleDot, and I defined it previously like so:var scrambleDot = new function() { //my code }. Here's the attempted implem ...

Trigger the fire event on .click() except when text is being selected

I am currently working on a chat box project and I want the input field within the message area to automatically get focused when the user clicks anywhere in the chat box. However, I don't want this functionality to interfere with text selection for c ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

Dealing with errors in Smart Query using Nuxt and Vue Apollo: How to navigate to specific error pages for 404, 400, or 500 errors and is it possible to catch

When utilizing Smart Query for redirection, how can we redirect to a 400 page? While working with Vue Apollo, I attempted the following: apollo: { queryName: { prefetch: true, query: wrongQuery, error(e ...

Troubleshooting AngularJS: Diagnosing Issues with My Watch Functionality

I need to set up a watch on a variable in order to trigger a rest service call whenever its value changes and update the count. Below is the code snippet I have: function myController($scope, $http) { $scope.abc = abcValueFromOutsideOfMyController; ...

Button activates SVG animation

Currently, I am working on an animation for a button using SVG. The animation utilizes the classes .is-loading and .is-success. However, when I click on the button, the animation does not execute as expected. I'm having trouble identifying the error w ...