[Vuejs]-This.$router is undefined inside Vue.extend() method

3👍

By creating a new Vue instance and mounting it, via new MarkdownContent().$mount(...), you are breaking the normal paradigm of parent/child relationship. The VueRouter plugin automatically sets the reference for this.$router for child components included in the template. But, by manually mounting the component, you lose that reference.

Instantiating and mounting a new component just to render a <router-link> tag seems very roundabout. But, if you really need do it this way, you just need to specify the router reference in the component definition object:

let MarkdownContent = Vue.extend({
  router,
  template: `<div>${routerLink}</div>`,
  mounted () {
    console.log(this.$router);
  }
});

Here’s a working codepen.

Leave a comment