Categories
Vue Answers

How to access $route.params in Vue.js?

Spread the love

Sometimes, we want to access $route.params in Vue.js.

In this article, we’ll look at how to access $route.params in Vue.js.

How to access $route.params in Vue.js?

To access $route.params in Vue.js, we access it from this in the options API.

In the composition API, we use the useRoute hook.

For instance, we write

<script>
//...
export default {
  //...
  methods: {
    get() {
      console.log(this.$route.params.id);
    },
  },
  //...
};
</script>

to get the value of the id route parameter with this.$route.params.id with the options API.

With the composition API, we use the useRoute hook by writing

<script>
import { useRoute } from "vue-router";
//...
export default {
  //...
  setup() {
    const route = useRoute();
    const id = route.params.id;
  },
  //...
};
</script>

We call useRoute to return the route object and then we get the value of the id route parameter with route.params.id.

Conclusion

To access $route.params in Vue.js, we access it from this in the options API.

In the composition API, we use the useRoute hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *