The Vue js error message states that the property '_router' is undefined and cannot be read

I'm attempting to transfer data and redirect from one component to another using vue-router.

Within my main component, I have a link that triggers a JavaScript function for routing.

<a href="javascript:void(0);" @click="switchComponent('ToolDetail')">click here</a>

methods: {
   switchComponent(comp) {
   this.$router.push({name:comp});
},

Currently, there is a console error when clicking the link for routing.

Uncaught TypeError: Cannot read property '_router' of undefined

In main.js, I've already imported my router-

import Vue from 'vue'
import App from './App.vue'
import router from 'vue-router'

Vue.config.productionTip = false
export const changeRoute = new Vue();
new Vue({
  render: h => h(App)
}).$mount('#app')

Vue.use(router)

Edit: Following guidance from @ittus, I made some changes like so-

In main.js-

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

In my HomeContent.vue-

<template>
    ...
    ..
    <a href="javascript:void(0);" @click="switchComponent('ToolDetail')">click here</a>
    ...
    ..
</template>
<script>
import ToolDetail from './ToolDetail.vue';
import VueRouter from 'vue-router';

...
..

methods: {
   switchComponent(comp) {
      const routes = [
        { path: '/ToolDetail', component: ToolDetail, name: 'ToolDetail' }
      ]
      const router = new VueRouter({
        routes
      })
      router.push({name:'ToolDetail'});
  },

...
..
</script>

Now, after clicking the link, nothing happens and no console errors appear. Could anyone provide assistance with this? Let me know if more details are needed.

Answer №1

Ensure that you are passing the router data to your Vue component.

import Vue from 'vue'
import App from './App.vue'
import Router from 'vue-router'

Vue.config.productionTip = false
export const changeRoute = new Vue();

Vue.use(Router) // Remember to include this before creating a new Vue instance

// For demonstration purposes
const router = new Router({
  routes: [
    {
      path: '/',
      name: 'ToolDetail',
      component: ToolDetail // Insert your component here
    }
  ]
})

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

For more detailed information, refer to the Getting Started document

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

Is it possible to utilize a jQuery function to count JSON data based on specific keys and values?

function calculateJSONObjFrequencyByKeyValue(obj, key, value) { var frequencyCount = 0; $.each(obj, function(i, item) { if(obj[i].key == value){ frequencyCount++; } }); alert(frequencyCount); } calculateJSONObjFrequencyByKeyValu ...

Error! Element not found in cloned iframe #2460, promise unhandled

Can you help me troubleshoot this issue? This is the code I'm working with: const section = document.createElement("section"); const myHTMLCode = "<p>Greetings</p>"; section.insertAdjacentHTML("afterbegin", my ...

Is it conceivable to generate fresh errors from an Ajax success event?

Whenever a server side error occurs in PHP, it is captured as a hash and then transmitted back to the client side using AJAX in the form of JSON. This way, the errors are effectively passed to the AJAX success event. ... catch ($e) { echo ( array("err ...

Utilize jQuery to locate the class that appears earlier in the DOM tree

Can someone assist me with retrieving the previous occurrence of a class within a specific portion of the Dom Tree using jQuery? If there is no previous occurrence, I would like to be informed about it. To clarify further, by "previous occurrence" I mean ...

Laravel has not been properly initialized

Recently, I've been exploring Laravel 5.3 and vue.js and I'm trying to make a GET request to fetch some user data from my database. I'm utilizing components in this project. Here is a snippet from my app.js file: require('./bootstrap ...

THREE.js Arrow with Enhanced Thickness and Dynamic lookAt() Functionality

I had the idea to create a "Thick Arrow" mesh, essentially an arrow similar to the standard Arrow Helper but with the shaft constructed using a cylinder instead of a line. tldr; do not just copy the Arrow Helper design; refer to the Epilogue section at t ...

Discover the process of visualizing data in table format with Vue.js!

This is a sample data format used to display information in a tabular format transformedData= { missingReports: [ { empId: "1234", empName: "Aarohi", monthTotalHours: { ...

What steps are needed to troubleshoot and resolve issues with integrating Google reCaptcha in an AWS Lambda

I'm encountering an issue with my lambda function which is intended to validate google recaptcha. Despite sending the correct data (the response) from the client, I consistently receive a console message stating "verification failed". Below is the cod ...

Comparing a number to the sum of numbers in JavaScript using VUE

Newbie in the world of JavaScript and VUE. In my data, I have a variable called numberOfItems with a value of 10. I am trying to check if this value is equal to the total sum of 5 different variables. var numberOfItems = 10 var destinations = (this.campa ...

Is there a way to deactivate or dim a specific hour in an HTML time form?

I am currently facing a challenge with my booking form. I need to find a way to grey-out or disable the hours/times that have already been booked by previous customers. This will help ensure that the next person can select a different time slot. However, I ...

Issue with CSRF Token discrepancy between cookies and HTML

Is there a proper way to retrieve the CSRF Token? In my Vue SPA, I am using Axios for login. I have converted everything to Vue components except for the Routes generated by `php artisan ui:auth`, so now I cannot use `@csrf` on my forms and have to send t ...

I am unable to access the state after setting it in useEffect in React. Why is this happening?

After rendering the component, I utilize socket io to send a socket emit in order to fetch data within the useEffect hook. Subsequently, I also listen for the data that is returned. However, upon receiving the data back from the socket, I update the stat ...

Pass information to a JavaScript function triggered by an onClick event

I have a JavaScript function that triggers on an event. Here's how it looks: function showArrays(event) { // This code snippet is extracted from Google Maps API Documentation // The getPath() method returns the MVCArray of LatLngs as this polygo ...

I'm curious about integrating Bengali language into an AngularJS script – any tips?

My app built with Angular is having trouble loading and displaying JSON data in Bengali language. I've made sure the server response is in UTF-8, but I still encounter the error "SyntaxError: Unexpected token in JSON at position 38" specifically whe ...

Learn how to retrieve JSON data from the Yahoo Finance REST API using Angular 2

Currently, I am in the process of developing an application that needs to fetch data from the Yahoo Finance REST API. To retrieve a table for the symbol "GOOG," I have implemented the following code: export class ActService{ act = []; url = 'http ...

Whenever the download bar emerges at the bottom, the slideshow content on the page suddenly shifts upwards

Each time the download bar shows up at the bottom, the slideshow content on the Homepage suddenly moves up. It returns to its original position after I close the download bar.https://photos.app.goo.gl/F482eMfkXyfEZkdA9. My assumption is that this issue is ...

Having trouble removing or adding a class to an HTML element?

I have a collection of three colored buttons. My goal is to allow users to select one button at a time, triggering it to be highlighted while the others are unselected. Each button corresponds to an object with a property called isSelected that can be set ...

Tips for verifying the existence of a row with a specific id using jQuery

Is there a way to use jQuery to verify if a table contains a row with a certain id? ...

Press the div, excluding the button - Vue

I have a basic div that spans 100% of the width, containing a button inside. The issue I'm facing is that when I add a click event to the div, the entire div becomes clickable (including the button within it). What I want is for the whole div to be ...

What is the best way to destructure an array enclosed within the Promise keyword in JavaScript?

Currently, I am attempting to extract information from a PSQL table using the following code: async function requestData() { var selectQuery = `SELECT "fName", "lName", "phoneNumber", "eMail" FROM public."Use ...