Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get 'id' from '$route.params'-URL to call it in useQuery

I’m working on a simple blog, I’m using Vue3 and Villus to send GraphQL queries. I build a component that shows all my posts. This works fine, in this component I send the ID in the URL for a single Post. For that, I build a blogpost_gql component. I need the ID for a GraphQL query. The ID is a part of the URL from Vue Router.

The URL looks like this:
text

The I tried to use: `

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.$route.params.id

`
This function doesn’t work in setup(). The static id in variables works well to query the schema. I figured out that this has something to do with lifecycle hooks. But I don’t find a solution.

This is my current code:

`

<script>
import { useQuery } from 'villus';
import ImageText from "@/components/Molecules/ImageText/ImageText";

export default {
  name: "BlogEntry_GraphQL",
  components: {ImageText},
  setup() {
    console.log('Hallo setup')
    const PostById = `
      query PostById ($id: String) {
        postById (id: $id){
            title
            publishDate
            author
            category
            imageUrl
            content
            id
            published
            slug
        }
      }
    `;
    const { data } = useQuery({
      query: PostById,
      variables: { id: this.$route.params.id },
    });
    return { data };
  },
};
</script>

`
I really hope, that you can help me.

I want to get the id from the URL. After this I want to use this ID to make a query.

>Solution :

In Vue3, the setup lifecycle hook is a bit special: it doesn’t have access to this, because the component hasn’t been created yet. So this refers to nothing.

To access the current route state, you have to use the exposed vue-router composables, as explained in the documentation: vue-router composition-api:

export default {
  setup() {
    const route = useRoute()
    const blogId = route.params.id
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading