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!
To get the query params from an above URL, we can use this. $route. query object inside our vue component <script> tag. Inside the vue component template, you can access it like this.
To get the current route path in nuxt, we can use this. $route. path or $this. $nuxt.
Nuxt automatically generates the vue-router configuration based on your file tree of Vue files inside the pages directory. When you create a . vue file in your pages directory you will have basic routing working with no extra configuration needed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With