"Error: Unable to access the property '$emit' of an undefined value" - VueJS

I'm currently working on implementing a basic authentication system in vuejs. I have a set of objects containing valid usernames and passwords. I am looping through this list to validate the entered username and password. If there is a match, I trigger an event and update the "authenticated" variable. However, I encountered an issue where I couldn't access the emit function inside the forEach loop during the login process.

Below is my Login.vue file:

<template>
    <div id="login">
        <h1>Login</h1>
        <b-form-input v-model="input.username" placeholder="Username"></b-form-input>
        <br/>
        <b-form-input v-model="input.password" placeholder="Password" type="password"></b-form-input>
        <br/>
        <b-button variant="primary" v-on:click="login()">Submit</b-button>
    </div>
</template>

<script>
    
export default {
    name: 'Login',
    data() {
        return {
            input: {
                username: "",
                password: ""
            }
        }
    },
    methods: {
        login() {
            var enteredUsername = this.input.username;
            var enteredPassword = this.input.password;
            if(enteredUsername !== "" && enteredPassword !== "") {
                this.$parent.mockAccount.forEach(function (element) {
                    if (enteredUsername === element.username && enteredPassword === element.password) {
                        this.$emit("authenticated", true)
                        this.$router.replace({name: "secure"})
                    }
                })
            }
        }
    }
}
</script>

<style scoped>
#login {
    width: 500px;
    border: 1px solid #CCCCCC;
    background-color: #FFFFFF;
    margin: auto;
    margin-top: 200px;
    padding: 20px;
}
</style>

And here is my App.vue file:

<template>
  <div id="app">
    <div id="nav">
      <router-link v-if="authenticated" to="/login" v-on:click.native="logout()" replace>Logout</router-link>
    </div>
    <router-view/>
  </div>
</template>

<script>

export default {
    name: 'App',
    data() {
        return {
            authenticated: false,
            mockAccount: [
                {
                    username: "a",
                    password: "a"
                },
                {
                    username: "rick",
                    password: "rick2018"
                },
                {
                    username: "nick",
                    password: "nick2018"
                },
                {
                    username: "paul",
                    password: "paul2018"
                }]
        }
    },
    mounted() {
        if(!this.authenticated) {
            this.$router.replace({ name: "Login" });
        }
    },
    methods: {
        setAuthenticated(status) {
            this.authenticated = status;
        },
        logout() {
            this.authenticated = false;
        }
    }
}
</script>

<style>
body {
    background-color: #F0F0F0;
}
h1 {
    padding: 0;
    margin-top: 0;
}
#app {
    width: 1024px;
    margin: auto;
}
</style>

I've encountered the following error: https://i.stack.imgur.com/wkLBt.png

Answer №1

ES5 functions have their own this, so make a change

this.$parent.mockAccount.forEach(function (element) {
  if (enteredUsername === element.username && enteredPassword === element.password) {
    this.$emit("authenticated", true)
    this.$router.replace({name: "secure"})
  }
})

You can either switch to an ES6 arrow function (which maintains the same this as the context they're defined in)

this.$parent.mockAccount.forEach((element) => {
  if (enteredUsername === element.username && enteredPassword === element.password) {
    this.$emit("authenticated", true)
    this.$router.replace({name: "secure"})
  }
})

or utilize explicit binding with Function.prototype.bind() (ES5):

this.$parent.mockAccount.forEach(function (element) {
  if (enteredUsername === element.username && enteredPassword === element.password) {
    this.$emit("authenticated", true)
    this.$router.replace({name: "secure"})
  }
}.bind(this))

or opt for using a closure:

const self = this;
this.$parent.mockAccount.forEach(function (element) {
  if (enteredUsername === element.username && enteredPassword === element.password) {
    self.$emit("authenticated", true)
    self.$router.replace({name: "secure"})
  }
})

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

Deleting data from Firebase in Angular can be easily done using the AngularFire library. By

I am attempting to remove specific values from my Firebase database. I need to delete this entry from Firebase: https://i.stack.imgur.com/CAUHX.png So far, I have tried using a button to trigger the delete function like this: <div class="single-bfunc ...

Sending basic HTML from Express.jsSending simple HTML content from an Express.js

Within my index.html document, I have the following: <input name='qwe'> {{qwe}} I am looking to send {{qwe}} in its literal form, without it being replaced by server-populated variables. How can I achieve this? My initial thought was to ...

What is the best way to transfer data from one function to another file in React without directly calling the component or using props?

filename - Header.jsx import { useEffect, useState } from 'react' import { getValue } from './Input' import TextField from '@mui/material/TextField'; export const Header = () => { const [search, setSearch] = useState( ...

Error: karma cannot locate the templateUrl for Angular component

I'm encountering some issues while running tests on angular directives with karma. The problem arises when the directive comes from a templateUrl and is not being translated properly. Here's my karma.conf.js configuration: 'use strict&apos ...

Creating a cron job that can be rescheduled using Node.js

I am utilizing the node-schedule package from GitHub to create cron jobs. While I have successfully created a basic scheduler, my goal is to make it reschedulable. Within my application, users can initiate tasks for specific dates. This can be easily achi ...

Discover the index of the row when the value in the dropdown list is updated

I'm faced with a challenge regarding an HTML Table that contains a dropdown list in every row. I would like the background of each row to change whenever the value in the dropdown list is modified. Below is the code snippet: <table id="table1"> ...

The instance of the Javascript Object Prototype losing its reference

I'm currently developing a small Javascript Object that will attach click listeners to specific elements, triggering an AJAX call to a PHP function. Everything is functioning as expected, but I want to execute a function once the AJAX response is rece ...

Multiple web pages utilizing Angular app/widget

I have successfully built a chat application similar to Google Hangouts. However, I am facing a challenge with the angular app/widget running on other pages when URL's are changed, causing the app to either remain fixed or restart on the new web page. ...

Create a pop-up window within a single controller using Angular.js

I followed a tutorial to create this code. I am interested in learning how to utilize just one controller for generating the dialog box. Currently, I am using two controllers for this project. Any guidance or tips would be greatly appreciated. View my cod ...

How can I stop popup labels from appearing in MapBox GL JS when I don't want them to be visible?

Having created an application using MapBox GL JS, I have placed numerous markers all around the globe. As the mouse hovers over these markers, a description box pops up, which is what I intended. However, I am encountering an issue where these labels flick ...

Pull the data from jQuery/JavaScript/AJAX and store it in the database using ASP.NET/C#

I am working on creating a form that includes textboxes and a five star rating feature. The goal is to save the data entered in the fields into a database upon submitting. While implementing the textboxes was straightforward, I am facing challenges with e ...

monitoring checkbox status in vue?

When using Vue, I have created dynamic checkboxes that display as shown below: <li v-for="element in checklist" :key="element.id" class="block w-full p-1"> <div v-if="element.taskId == task" clas ...

When attempting to import my JSX file into page.js, I continue to encounter the error "module not found." How can I troubleshoot and resolve this issue in Visual Studio Code

I recently created a new file called mysec.jsx in the components folder of src. I then used the export function to properly export it. However, when I tried to import this file in page.js using the import function, I encountered an error message that said: ...

Navigating through sections in NextJS-14: Utilizing useRef for seamless scrolling

In the past, I had developed an older portfolio website using Vite React + TS and implemented useRef for scrolling to sections from the Navbar. Now, my goal is to transition this portfolio to NextJS 14. I transferred my old components and style folders in ...

When attempting to submit data, the Magnific Popup page is restored to its default format

I am facing an issue with my Magnific Popup page: function dataLink(){ $.magnificPopup.open({ items: { src: 'datapage.html', type: 'ajax' }, closeOnContentClick : false, clos ...

Ignore one specific file when importing all files in Angular 7

In my Angular 7 project, I am utilizing C3 and importing all the necessary files at the beginning of my .ts component file using a wildcard. import * as c3 from 'c3'; While this method works well overall, I encountered an issue where my CSS ove ...

Giving identification to a pair of elements located within the same column

Struggling with assigning IDs to two elements in a single column - a dropdown and a text element. Managed it in the first scenario, but encountering issues in the second one. Seeking assistance on this matter. Scenario 1: <td> <sele ...

When I engage with the input field, it ceases to be in focus

Here is the code I've been working on: https://github.com/Michael-Liendo/url-shortener/blob/main/src/pages/index.js If you want to see the issue for yourself, check it out at: ...

When using a Vue.js component, the value of this.$route can sometimes come back

I am attempting to retrieve the parameters from the URL and pass them into a method within a Vue component. Despite following advice to use this.$route, I am consistently getting an 'undefined' response. I have tried various solutions suggested ...

Using an if statement within a map function in a React component

I am facing a challenge with using an if statement inside a map function without changing the return value. Here is my code snippet: this.example = this.state.data.map((item) => { return( <div> {if(1 + 1 == 2){ dat ...