«Ошибка типа: невозможно прочитать свойство $ emit неопределенного» - VueJS - PullRequest
0 голосов
/ 09 апреля 2019

Я пытаюсь реализовать простую аутентификацию в vuejs.У меня есть список объектов, в которых у меня есть подлинное имя пользователя и пароль.Я перебираю этот список и проверяю введенные имя пользователя и пароль.Если есть совпадение, то я отправляю событие и обновляю свою переменную, прошедшую проверку подлинности.Но проблема внутри логина в цикле forEarch, я не могу получить доступ к emit.

Это мой файл Login.vue

<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>
        <!--<input type="text" name="username" v-model="input.username" placeholder="Username" />-->
        <!--<input type="password" name="password" v-model="input.password" placeholder="Password" />-->
        <!--<button type="button" v-on:click="login()">Login</button>-->
    </div>
</template>

<script>
    /* eslint-disable no-console */
    // import Vue from 'vue'
    // import BootstrapVue from 'bootstrap-vue'
    // import 'bootstrap/dist/css/bootstrap.css'
    // import 'bootstrap-vue/dist/bootstrap-vue.css'
    //
    // Vue.use(BootstrapVue)
    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"})
                        }
                    })
                }
                    // for (var keys in this.$parent.mockAccount) {
                    //     console.log(keys[0].username)
                    //     if (this.input.username === keys[0] && this.input.password === keys[1]) {
                    //         this.$emit("authenticated", true);
                    //         this.$router.replace({name: "secure"})
                    //     }
                    // }
                    // if (!this.authenticated) {
                    //     alert("The username or password does not match!!")
                    // }

                //     if(this.input.username === this.$parent.mockAccount.username && this.input.password === this.$parent.mockAccount.password) {
                //         this.$emit("authenticated", true);
                //         this.$router.replace({ name: "secure" });
                //     } else {
                //         console.log("The username and / or password is incorrect");
                //     }
                // } else {
                //     console.log("A username and password must be present");
                // }
            }
        }
    }
</script>

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

Вот мой файл App.vue

<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>

Это ошибка, которую я получаю enter image description here

1 Ответ

1 голос
/ 09 апреля 2019

Функции ES5 имеют свои собственные this, поэтому измените

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

либо на функцию стрелки ES6 (которая имеет тот же this, что и контекст, в котором они определены)

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

или используйте явное связывание с 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))

или используйте замыкание:

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"})
  }
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...