VueJS Router error: The variable $route is undefined

Check out my component:

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

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

Now take a look at 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);

But when I try to run this app, an error occurs:

ReferenceError: $route is not defined

I attempted using this.$route but it doesn't seem to work. I typically use arrow functions, but in this case, the following code works:

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

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

If you have any suggestions on how to solve this issue, please let me know. Thank you!

Answer №1

Make sure to include vue-router in your main Vue app.

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

After including vue-router, you can proceed with the route declaration.

Answer №2

Make sure to include the router in your Vue instance setup.

You can add it in your main.js, app.js, or index.js files (the entry point of your application).

const app = new Vue({
  router
})

For more information, refer to the official documentation.

Answer №3

Avoid using arrow functions when declaring methods

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

I found success with this approach.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to set the minimum width of a div depending on its contents

As I work on my website, I encountered an issue with a div containing a table. The div expands to full width, but when I resize the screen, it shrinks causing the content to overlap. I am looking for a solution where the minimum width of the div adjusts b ...

Insert a new element at the current scroll position without disrupting the existing scroll or view

My goal is to replicate the functionality of the Twitter Mac client. I have a scrollable box with a fixed height and multiple blocks inside. I want to add a new block before all the others, but keep it invisible to the user so they have to scroll to the to ...

The function `map` cannot be applied to `this.state.[object]`

It seems like I might be overlooking a simple mistake, but I keep encountering this.state.iata.map is not a function , even though I have bound the context to all functions where I need to access that state. Additionally, the iata state is an array, s ...

Ensure all <li> tags within a HTML document exhibit consistent jquery mousedown and hover effects, abstaining from the assignment of unique IDs to each

I understand that this approach might not be correct, but I wanted to create a simulation of what I am trying to achieve. Is there a way for each <li> element within a specific <ul class="myul"> to have separate mousedown, mouseout, hover effe ...

The concept of overloading operators in V8

Here's a question that I've been pondering, but couldn't seem to find any answers for on Google. While it may not be achievable in pure JavaScript, let's say I'm developing a container class in V8 and then returning that class bac ...

The maximum value of the slider corresponds to the total number of elements in the array

As I work on constructing a Material UI Slider, I have a specific requirement. I want the maximum value of my slider to dynamically adjust according to the number of items in an array of options. ['Answer1', 'Answer2', 'Answer3&ap ...

Capturing all requests - javascript

I have a webpage called sample-page.html that contains 2 links: sample-page.html - link1 (GET, AJAX) - link2 (GET, new page) Clicking on link1 triggers an AJAX GET request and remains on the same page (sample-page.html). Clicking on l ...

"Enhance your website with the powerful combination of SweetAlert

I'm having trouble getting my ajax delete function to work with SweetAlert. I can't seem to find the error in my code. Can someone help me figure out how to fix it? function deletei(){ swal({ title: 'Are you sure?', ...

How to dynamically alter a PHP variable using a JavaScript button click on the existing webpage

I've spent the last hour scouring stackoverflow for answers to my problem, but trying out solutions has only resulted in errors - perhaps because I'm attempting to implement it on the same page. I've experimented with saving the value to a ...

Adding fewer components to your current Angular 5 project

I have a JS Fiddle showcasing a CSS chart. How can I integrate LESS into my current Angular 5 project to make use of this chart? Also, where should I place the JavaScript and references to the LESS file from this example within my Angular component? The li ...

Adding event listener to a dynamically created video element

Could you provide any insight as to why I'm encountering an error message "Can't create event listener on null" when using the following code: var my; my.newVidObj = document.createElement('video'); my.newVidObj.src = "vid- ...

Jquery UI slider malfunctioning would require troubleshooting

I am currently working on implementing slider functionality with jQuery. The slider is visible and functioning properly in terms of taking in values, however, the values are not displayed on the screen as expected. I have used console.log to track the ui.v ...

Issue with Firefox compatibility in Backbone.js

Greetings! I am currently utilizing Backbone.js and require.js for my application, experiencing difficulty with template rendering in Firefox. Interestingly, it works without issues in both Chrome and IE. Allow me to present the code responsible for rende ...

employing document.write() specifically for a designated division

This is the coding: $(document).ready(function(){ var Jstr = { "JSON" : [ { "Eid" : 102,"Ename":"", "Ecode" : "<input type ='text'/>", "Eprops": {"name": "", "value":"", "maxlength":""}} ] } ; $(".search").click(funct ...

What is the best way to display the currently selected value in a Vue select drop down?

Is there a way to make the selected item in a custom component dropdown appear, similar to this Vue.js question? I have debug output within my single file component (SFC). <script> export default { props: ['modelValue', 'options&apos ...

Navigating a JSON object using jQuery

My current project involves sending a Json response to an Ajax function within my webpage. The structure of the Json response is as follows: {"one": 21, "two": 10, "three": 19, "four": 100} With this setup in place, I am now in the process of developing ...

What causes the namespace to shift when utilizing npm for installing a library?

I've been attempting to integrate whammy.js into a project. The initial line in the source code is window.Whammy = (function(){ yet, after running npm i and inspecting node_modules, I discovered global.Whammy = (function(){ https://github.com/anti ...

What is the process for obtaining a compilation of warnings from the next.js terminal?

While running my project on VScode, I noticed a series of warnings appearing in the terminal. One specific warning that caught my attention is: The `bg-variant` mixin has been deprecated as of v4.4.0. It will be removed entirely in v5. on line 8 ...

Kendo's data-bind onclick feature functions properly on web browsers but fails to work on mobile devices

As a newcomer to Kendo and JavaScript, I may be missing something obvious... In one of my list entries, I have a simple call like this: <li style="margin: 0.5em 0 0.5em 0"> <a href="#transaction-details" data-bind="click: onB ...

Tips for storing and replicating jQuery events

I am working on saving jQuery events in a database. // This Function is called On Click function trackevent(event){ window.events.push(event) } $.each(window.events, function(i, item){ console.log(i +" - "+ $.parseJSON(item)); }); The events a ...