How to get route url params in a page in Nuxt2 and 3?
Asked Answered
C

9

89

I am using Nuxt.js, and have a dymanic page which is defined under

pages/post/_slug.vue

So, when I visit the page url, say, http://localhost:3000/post/hello-world, how can I read this slug parameter value inside my page.

Currently I am geting it using asyncData as follows:

  asyncData ({ params }) {
    // called every time before loading the component
    return {
      slug: params.slug
    }
  }

This is working fine, but I think this is not the best way, and there should be a better way to make the parameter available to the page. Any help is appreciated!

Cangue answered 2/1, 2018 at 22:9 Comment(4)
could you tell you want use params for what?Jacobinism
I use this param to query and fetch some data from an API.Cangue
Then I think your way is the best way!Jacobinism
ok thanks! I will continue to use this method till we find a better one :)Cangue
O
132

For Vue2 and Nuxt2

In the .vue file, to get the Vue router route object:

this.$route

( notice the Vue router is under the this.$router object)

The $route object has some useful properties:

{
  fullpath: string,
  params: {
    [params_name]: string
  },
  //fullpath without query
  path: string
  //all the things after ? in url
  query: {
    [query_name]: string
  }
}

You can use the $route object like this:

    <script>
    export default {
      mounted() {
        console.log(this.$route.fullPath);
      }
    };
    </script>

the url path params is under the route.params, as in your case route.params.slug

    <script>
    export default {
      mounted() {
        console.log(this.$route.params.slug);
      }
    };
    </script>

the Vue mouted hook only run on client, when you want to get the params on server, you can use the asyncData method:

    <script>
    export default {
        asyncData({route, params}) {
            if (process.server) {
                //use route object
                console.log(route.params.slug)
                //directly use params
                console.log(params.slug)
            }
        }
    };
    </script>

But, pay attention:

It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes. ref

If you don't need the params information on server, like you don't need to get data based on the params on server side, I think the mounted hook will suffice.

Ondrea answered 16/4, 2019 at 14:59 Comment(1)
params is not right, it is queryBac
U
27

To read params from URL you should use this way in Nuxt:

this.$route.query.<name_of_your_parameter_in_url>

For example

URL: https://example.com/example/?token=QWERTYUASDFGH

with this line of code, you can read token:

this.$route.query.token

and give you QWERTYUASDFGH.

Understandable answered 14/7, 2020 at 6:34 Comment(2)
query is the correct answer for me in nuxtjsBac
Correct me if I'm wrong, params != query. example.com/post/{id} would be a parameter, example.com/post?id=123 would be a query.Fulvous
M
13

With the release of a stable version of Nuxt3, I feel like updating with an answer using the composition API.

This is how you would access all the interesting parts of the current route in any .vue file

<script setup>
const route = useRoute()
</script>

<template>
  <pre>{{ route }}</pre>
</template>

route getting the following in case of going to http://localhost:5678/about?fruit=watermelon

{
  "path": "/about",
  "name": "about",
  "params": {},
  "query": {
    "fruit": "watermelon"
  },
  "hash": "",
  "fullPath": "/about?fruit=watermelon",
  "matched": [
    {
      "path": "/about",
      "name": "about",
      "meta": {},
      "props": {
        "default": false
      },
      "children": [],
      "instances": {},
      "leaveGuards": {
        "Set(0)": []
      },
      "updateGuards": {
        "Set(0)": []
      },
      "enterCallbacks": {},
      "components": {
        "default": {
          "__hmrId": "0a606064",
          "__file": "/home/kissu/code/test/n3-default/pages/about.vue"
        }
      }
    }
  ],
  "meta": {}
}

If you use the Vue devtools, you can also click on a component and find the instance via the console (helpful if you want to quickly inspect the object). It gives a bit more details than the Routes tab.

enter image description here

More info available here: https://v3.nuxtjs.org/api/composables/use-route#useroute


With Options API, it would be the following (as in the console)

<script>
export default {
  mounted () {
    console.log('route object', this.$.appContext.app.$nuxt._route.query)
  },
}
</script>

PS: there is maybe a shorter way that I don't know yet.

PS2: I'm always confused between query params and "route params", hence this memento for a difference could be useful.

Melodeemelodeon answered 12/5, 2022 at 8:12 Comment(0)
C
4

Simply you can access routing parameters

for global uses but it is not good practice:

window.$nuxt._route.params

for local uses under pages/components/layout etc, Always we should practice like below

this.$route

or

this.$nuxt._route.params

Croatian answered 16/1, 2019 at 5:1 Comment(2)
This seems like a very bad practice as it's never mentioned in nuxt js documentations !Attested
$nuxt.$route is documented though.Uhf
M
4

If you are in the store context (for example actions.js), you can access the query parameters like this:

this.$router.currentRoute.query['param_name']
Mahlstick answered 6/11, 2019 at 9:9 Comment(2)
This help me a lot, ty. But better use this.$router.currentRoute.params.param_nameEmendation
A query params is not a path variable. Here, OP is looking for the path variable params as per se. Yeah, the working is poor on this one.Melodeemelodeon
P
2

Other answers are mostly enough, if you want to access route info inside apollo smart query:

  apollo: {
    items: {
      query: jobsBy,
      variables() {
        return {
          clientId: this.$route.query.id
        }
      },
    }
  }
Praxiteles answered 2/9, 2019 at 23:0 Comment(0)
C
1

Declaring dynamic routes
In nuxt2, underscore _ was used for dynamic routes, in nuxt3, instead of underscore _ the dynamic routes now use the square brackets []

Accessing params
In nuxt2, the route params can be accessed on $route object
e.g this.$route.params
In nuxt3, the params can be destructured from useRoute composable
e.g. const { params } = useRoute()

Concretize answered 20/12, 2022 at 11:52 Comment(0)
W
0

To the best of my knowledge, this already is the best way, if not the only one to do that. But I could suggest an slightly different approach that maybe fit to your needs. Use the asyncData method to retrieve the data from the server instead of put a param at your VM and process later, if is your case. Then, you can handle the result data at the presentation logic and not any kind of request. On the other hand, also you could use, fetch if you don't want to pass anything to the VM or use a middleware instead, according to your needs.

Wightman answered 13/7, 2018 at 4:23 Comment(0)
E
0

The best way for me is :

async asyncData(context){
      const query_params=context.route.query;
}
Emotion answered 25/1, 2021 at 17:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.