4
votes

This is my component:

const Vue = require("vue/dist/vue.js");
const qs = require("querystring");

module.exports = Vue.component("Page",function(resolve){
    console.log($route);
    let id = this.$route.params.id;
    fetch("/getPage.json",{
        method:"POST",
        body:qs.stringify({
            id
        })
    }).then(r=>r.json())
    .then(j=>{
        console.log(j);
        resolve({
            template:`<h1>`+JSON.stringify(j)+"</h1>"
        });
    })
});

And this is my router:

const router = new VueRouter({
	mode:"history",
	routes:[
		{
			path:"/",
			component:Home
		},
		{
			path:"/me",
			component:Me
		},
		{
			path:"/create-page",
			component:createPage
		},
		{
			path:"/p/:id",
			component:Page
		}
	]
});
Vue.use(VueRouter);

When i run this app i get:

ReferenceError: $route is not defined

I tried using this.$route but it's not working. I'm using an arrow function. When i do this it works:

const Vue = require("vue/dist/vue.js");

module.exports = Vue.component("Page",function(resolve){
  resolve({
    template:`<h1>{{$route.params.id}}`
  });
});

Please help me figure out how to fix this.

3

3 Answers

2
votes

in your main vue app

new Vue(...)

you have to use vue-router first

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
...
new Vue(...)
...

and the go ahead with route declaration

1
votes

you forgot to add router in Vue instance

in you main.js or app.js or index.js (entry point)

const app = new Vue({
  router
})

documentation

0
votes

You should NOT use arrow functions

data: function() {
    return {
      usertype: this.$route.params.type
    };
  },

This worked for me.