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