How to fix $route is not defined with Vue.js?

Sometimes, we want to fix $route is not defined with Vue.js.

In this article, we’ll look at how to fix $route is not defined with Vue.js.

How to fix $route is not defined with Vue.js?

To fix $route is not defined with Vue.js, we should make sure have Vue Router in our Vue project and we use regular functions and this.$route in our methods and hooks.

For instance, we write

import Vue from "vue";
import Router from "vue-router";
//...
Vue.use(Router);

const router = new VueRouter({
  routes: [
    { path: "/videos", name: "allVideos", component: Videos },
    { path: "/videos/:id/edit", name: "editVideo", component: VideoEdit },
  ],
});

new Vue({
  el: "#app",
  router,
  //...
});

to add the Router plugin with Vue.use and add router into our Vue instance.

And then in our component methods, we write something like

<script>
//...
export default {
  //...
  data() {
    return {
      id: this.$route.params.id,
    };
  },
  //...
};
</script>

where data is a regular function instead of an arrow function.

Conclusion

To fix $route is not defined with Vue.js, we should make sure have Vue Router in our Vue project and we use regular functions and this.$route in our methods and hooks.