"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

Troubleshooting problem with POST method in Laravel combined with Vue and Axios

In the midst of a Laravel 5.6 project hosted on a VPS (dubbed "production" although there is no specific environment created), we have set up Plesk and Github for manual deployment of the web app from our local setups to the server. The current issue aris ...

The Vue computed property is failing to retrieve the data it needs

I'm having trouble with the computed() property not retrieving data. Data was initialized in the created() property. Am I missing something here? Any guidance on how to resolve this issue would be greatly appreciated. const randomPlayers = { temp ...

What impact do the input values of an Angular reactive form have on the DOM?

I am currently working on developing a UI wizard app using Angular (reactive forms) version 6/7. The main purpose of this app is to enhance the product page of an ecommerce platform such as Shopify or WordPress. I am utilizing angular material radio inputs ...

Using AngularJS location.path for unique custom URLs

Control Code: $scope.$on('$locationChangeStart', function () { var path = $location.path(); var adminPath = '/admin/' ; if(path.match(adminPath)) { $scope.adminContainer= function() { return true; }; }); HTML <div clas ...

Discover an Easy Way to Scroll to the Bottom of Modal Content with Bootstrap 5 on Your Razor Page

Currently, I am developing a web application that utilizes Razor Pages and Bootstrap 5 modals to showcase dynamic content. The challenge I am facing is ensuring that the content inside the modal automatically scrolls to the bottom when the modal opens or w ...

Is it possible to create a personalized serialize form when sending an AJAX POST request

How can I format form data on an AJAX POST request differently than the default $("#formid").serialze()? The current result is not suitable for my needs, as it looks like this: `poststring="csrfmiddlewaretoken=bb9SOkN756QSgTbdJYDTvIz7KYtAdZ4A&colname= ...

What naming convention do you recommend for mixin functions to ensure clarity and consistency?

In the past, I've struggled with locating where methods, computed values, and other components are defined when using multiple mixins. Is there a recommended standard practice for resolving this issue? One way to approach this problem is as follows: ...

Reorganize items that extend beyond the list into the next column using Bootstrap

I have a row with two columns, where Column 1 currently contains 7 list items under the ul tag. However, I want to display only 5 list items in Column 1 and automatically move the remaining items to the next column (i.e., Column 2). Is there a way to ach ...

Discovering the Vue app container div attribute

I am currently working on a Java app that generates pages server-side based on certain data, such as a publisher for a specific entity. I want to develop a reusable Vue component that can call an API method to request data about the entity that is being vi ...

Can you provide guidance on effectively utilizing a Pinia store with Vue3, Pinia, and Typescript?

I'm currently facing challenges while using the Pinia store with TypeScript and implementing the store within a basic app.vue Vuejs3 option api. Here is my app.js file: import {createApp} from 'vue' import {createPinia} from "pinia&quo ...

Accepting multiple file inputs in a form without using a selector, but instead utilizing the 'this' keyword or finding an alternative approach

When dealing with single file uploads, you can access the file input using this.image <form id="form"> <input type="file" name="image"> <input type="submit" name="submit"> </form> $ ...

I am having trouble getting PHP to parse JSON in the way I need

Currently, I am working on a hobby project that involves an API for accessing data. While everything seems to be functioning well on the other ends, I am facing an issue with the JSON array format. I need the JSON array to not have brackets so that I can e ...

Express JS is experiencing difficulties with the functionality of the iframe

When I'm using iframe in HTML, it works perfectly fine: <iframe src="main.html" height="100px"></iframe> But when I use Iframe in Express, it shows an error: <iframe src="main.html" height="100px&qu ...

Sending Angular base64 image data to the server

I am encountering an issue while attempting to upload a base64 image from Angular to ExpressJS. The image is being created using html2canvas to generate the base64 representation. When I try to upload the imageData in its current format, I receive an error ...

Creating dynamic object rotation based on a new pivot point using Three.js

In Three.JS, I've successfully created a spiral with downward movement. However, I am struggling to implement the knocking motion. https://i.sstatic.net/VrykN.gif var planeGeometry = new THREE.PlaneGeometry(10,10); var planeMaterial = new THREE.Mesh ...

Deciphering the intricacies of the http request

I encountered an issue while trying to send a POST request using jQuery AJAX. Upon making the request, I received the following error: XMLHttpRequest cannot load. Response for preflight has invalid HTTP status code 403 Now, I am unsure if the mistake i ...

Is it possible to send an ajax request to a user control file with the extension .ascx?

I am trying to interact with a user control on my page through ajax. Is it possible to make an ajax request directly to the user control (.ascx) instead of .aspx or .ashx files? ...

Which one is better: JSON in PHP or JSON in Javascript?

In my current project, I am working on a website that utilizes a PHP function to retrieve JSON data and present it on the webpage. However, I have noticed that when the page loads, it freezes until the response is successfully fetched, creating a visual di ...

Implementing webpack and service workers in Vue.js: a comprehensive guide

At this moment, the package.json for my vue app looks like this: { "name": "App", "version": "0.1.2", "private": true, "scripts": { "serve": "vue-cli-service serve" ...

Using React hooks to update the state of an array from one component to another

I am currently working on a MERN blog website project and I've encountered an issue while trying to update comments on a post. I'm editing the comment from another component but facing difficulty in updating the state after making changes. Would ...