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

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

Leave a Reply