vue.jsapolloapollo-clientvue-apollo

How i can get router params in apollo ? [VUE3]


here is my component script on VueJS. I want to know how to get router params in my apollo component to search item whith these params. The idea is to replace 953 by the id of the page. If you have any questions, ask me ! I'm using createRouter, createWebHashHistory from vue-router and VueJS 4.

Thanks for help.

<script>
import gql from "graphql-tag";
// import { useRouter } from "vue-router";
import TemplatePresentationPage from "./TemplatePresentationPage.vue";
export default {
    name: "PresentationPage",
    apollo: {
        entry: gql`
            query entry {
                entry(id: 953) {
                    id
                    title
                }
            }
        `,
    },
    components: { TemplatePresentationPage },
    setup() {
        return {};
    },
};
</script>

Solution

  • If your routes looked like this

    const routes = [{ path: '/user/:id', component: User }]
    

    then to get that id param on your component you just do as below

    const User = {
       // make sure to add a prop named exactly like the route param
       props: ['id'],
      template: '<div>User {{ $route.params.id }}</div>'
    }
    

    and this works on your template as well

    <template>
       <div>User {{ $route.params.id }}</div>
    </template>
    

    But as for your case, it seems like you want to use it on your setup() function. The way you access it is as below

    import { useRoute } from 'vue-router';
    
    export default {
     setup(){
      const route = useRoute();
      //console.log(route.params.parameterName)
    }
    }