Vue.js: Accessing the $router object returns undefined

I'm encountering an issue with

this.$router

being undefined in App.vue and other components. I've been struggling to find a solution.

Here's a snippet of my main.js:

Vue.use(VueRouter);
Vue.use(VueResource);

const router = new VueRouter({
    routes: Routes,
    mode: 'history'
});

new Vue({
    el: '#app',
    render: h => h(App),
    router
});

And here is my router.js file which I'm importing in main.js:

export default [
    {path: '/', component: Home, name: 'home'},
    {path: '/home', component: Home, name: 'home2'},
    {path: '/user/login', component: Login, name: 'userLogin'}
];

Thank you :)

Edit

Initially, I was attempting to access it within script tags like this:

<script>
    import HeadNavBar from './components/HeadNavBar.vue';
    import SideBarNav from './components/SideBarNav.vue';
    import Home from './components/Home.vue';


    console.log(this.$router,pus); //the undefined type

    export default {
        name: 'app',
        data() {
            return {
                isLogin: true
            }
        },
        components: {
            'app-headnav': HeadNavBar,
            'app-sidebarnav': SideBarNav,
            'app-home': Home
        }

    }
</script>

But when I moved it into the methods section, I achieved the desired outcome:

export default {
    name: 'app',
    data() {
        return {
            isLogin: true
        }
    },
    components: {
        'app-headnav': HeadNavBar,
        'app-sidebarnav': SideBarNav,
        'app-home': Home
    },methods: {
        myFunc: function() {
            console.log(this.$router,pus); // this gave result
        }
    }
}

Answer №1

I encountered the undefined error with this.$router only when utilizing an arrow function (which could be the case for you as well), something that is not recommended according to the Vue documentation:

Avoid using arrow functions on options properties or callbacks, like

created: () => console.log(this.a)
or
vm.$watch('a', newValue => this.myMethod())
. Since arrow functions are bound to the parent context, it will not refer to the Vue instance causing potential errors such as
Uncaught TypeError: Cannot read property of undefined
or
Uncaught TypeError: this.myMethod is not a function
.

For instance, here's how the mounted callback successfully logs this.$router:

<script>
  export default {
    name: 'app',

    // AVOID USING ARROW FUNCTIONS HERE
    // mounted: () => {
    //   console.log({router: this.$router});
    // },

    mounted() {
      console.log({router: this.$router});
    }
  }
</script>

Answer №2

Although this may be considered outdated, I wanted to share a solution to a common issue that I came across in my vue/meteor project.

When working with functions and handlers in this setup, it's important to note that "this" refers to the function's target. This means that when using `this.$router`, it's actually looking for `$router` within the function or its target itself.

    ///////NOT WORKING ///////////
  mounted: function () {
    $(document).on('click', '.element', function(){
             //this is recognized as 
             this.$router.push(PATH)
        });
  },


    ////////WORKS THIS WAY//////////
  mounted: function () { 
    //define router outside of the function.
    var navigate = this.$router;

     $(document).on('click', '.element', function(){
        navigate.push(PATH)
     });
  }

Answer №3

Encountering the same error, I managed to resolve it by importing the router files into my component as shown below:

Importing router files/configuration in my component :

import router from '../router'

This allows me to use it like this:

router.replace('home')

This should make it work smoothly.

Here is my complete code snippet:

<script>
import router from '../router'
export default {
  methods: {
  signIn: function () {
    firebase
    .auth().signInWithEmailAndPassword(this.email, this.password).then(
      function (user) {
        router.replace('home')
      },
      function (err) {
        alert('Sorry, ' + err.message)
      }
    )
  }
 }
}
</script>

Answer №4

When the component is imported, the code console.log(this.$router,pus) before the export statement is executed. This occurs prior to the creation of the component, resulting in this being an empty object {}.

If you need access to this.$router, it should be obtained within the methods of the export object.

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

Displaying an HTML/CSS image layered on top of another image with a fixed navigation bar

I've run into an issue with my webpage layout. I have a fixed navigation bar and an image displayed, but now I want to add another image on top of the existing one. However, when I use "position: relative" and position:absolute", the two images end up ...

Implementing a Reset Button to Clear Checkboxes with PHP or JavaScript

I'm looking for help with setting up a button to reset the checkboxes on my preferences page. UPDATEL: Here's more information: The solutions provided should only affect checkboxes that are currently selected, not those enabled onLoad. This is ...

Setting a random number as an id in the constructor in Next JS can be achieved by generating a

What steps can be taken to resolve the error message displayed below? Error: The text content does not match the HTML rendered by the server. For more information, visit: https://nextjs.org/docs/messages/react-hydration-error Provided below is the code i ...

apply jQuery to add a class to the parent element when clicked

I am currently facing an issue with my code. It was working fine in jsFiddle, however, when I try to use it outside of fiddle, I am getting errors and it's not working properly. $('.down-photo').click(function() { $(this).parent(&apos ...

Using JQuery and CSS to handle multiple hyperlink links with a single action

UPDATE: Issue resolved, thanks for the help. It is working fine now: http://jsfiddle.net/c3AeN/1/ by Sudharsan I have multiple links on my webpage, all in a similar format like this: note: When I say 'similar format', I mean that all links share ...

What problems are being caused by this specific way of assigning variables?

What is the difference in variable assignment when it is inside an object and the "this" variable refers to that object? var prop = this.properties; var properties = this.properties; Compared to: var prop = properties = this.properties; Switching t ...

Node.js Apple in-app purchase (IAP) receipt validation

Trying to implement Node.js from this repository for my IAP Receipt Validation, but encountering an error in the server's log: "The data in the receipt-data property was malformed." Seeking assistance on properly sending a base64 string to Node.js an ...

Why does npm/yarn claim that the "license" in my package.json is missing when I have it listed?

Whenever I run yarn install, a warning pops up indicating that there is no license field, despite having defined one as follows: $ jq . package.json { "name": "license-example", "version": "1.0.0", "main": "index.js", "license": "UNLICENSED", " ...

An issue occurred while evaluating the Pre-request Script: Unable to access the 'get' property of an undefined object

I need help accessing the response of my POST request in Postman using a Pre-request Script. Script below : var mobiles = postman.environment.get("mobiles"); if (!mobiles) { mobiles =["8824444866","8058506668"]; } var currentMobile = mobiles. ...

Error: Expecting only one React element child to be passed into React.Children.only() function

I am encountering an issue while attempting to construct a web table using the antd library. The exact error message reads: "react.development.js:1251 Uncaught Error: React.Children.only expected to receive a single React element child". I have been stru ...

Trigger Vue method when the size of a div element changes

Is there a way to trigger a method every time the dimensions (width or height) of a div element change? <template> <div> </div> </template> <script> export default { methods: { updateSize() { // ...

The premature reveal of the back side in the Kendo UI flip effect on Internet Explorer

Currently, I am in the process of creating a BI dashboard for a business application using JavaScript Kendo UI version v2014.1.416. Unfortunately, I have encountered an issue with certain visuals while testing on IE11. I must mention that due to practical ...

What is the best way to check for changes in value using the onchange

The function is encountering an error and failing to execute. Despite my attempts to check for the onchange property in order to prevent errors, I keep receiving an error message stating "Cannot read property 'onchange' of undefined." Below i ...

methods for pausing music through a toggle button in a React JS application

I am facing an issue with the following shortcode for playing a song on a toggle button. The problem occurs when I try to pause the music and it does not stop as expected. import { React, useState } from 'react'; import './audio.css&apos ...

Adjust the width of the TinyMCE Editor to automatically resize based on the content being

Is it possible for TinyMCE to adjust the content within an absolutely positioned container and update the width while editing? <div class="container"> <textarea>This is my very long text that should not break. This is my very long text tha ...

Ajax Syntax Error: Unexpected Token U

I have been struggling all day with an issue while trying to send json data via ajax to Express. Here is how my ajax code looks like: $('#saveClause').click(function () { var username = document.getElementById('postUserName').inne ...

Working with AJAX requests in .NET Core

Clicking on the "Forgot Password" link should open a popup. Upon clicking the "Send email" button in the popup, a POST request should be sent and then move to the next popup for verifying the OTP. Here is the code for the link that triggers the modal to o ...

Arranging a JavaScript Array using the Split Method

Currently, I am working with an array that has the following structure: var testArray = ['name1:13', 'name2:15', 'name3:13']; My goal is to sort this array based on the numbers located to the right of the colon. At the mome ...

JavaScript tri-state toggling

After devising 2 buttons, each intended to toggle a heading or paragraph, I encountered a slight issue. When using the 'Toggle Para' button, the switch occurs between 2 paragraphs upon 2 clicks. However, on the third click, I desire for both para ...

How can I load a function from the HTML file that is being loaded using .load() in jQuery?

Within my main window main.html, there is a div button that, when clicked, loads another html file into a large div. This is achieved using the .load() function: $('#mainpanel').load("search.htm"); The "search.htm" file contains a function cal ...