简体   繁体   中英

Array fetch using vue.js & js

New to vue & js. Trying to create a simple login authentication. The 'if' works for array [0] but not for [1][2][3] etc. I want it to check all arrays for a match.

Here is my code:

Any help will be appreciated.

var app1 = new Vue({
    el: '#app',
    data: {
        name: null,
        password: null,
        users: [],
    },
    mounted() {
        this.users = JSON.parse(localStorage.getItem('users'));
    },
    methods: {
        login() {
            if (this.name == this.users[0].text && this.password == this.users[0].password) {
                alert("success");

            }
             alert("failed");
        }

    }

}); ```

First off, I hope you're doing this as a practice, just for yourself, or don't really care about security. User credentials should always be checked server-side.

That being said, you can loop over the users until you find one that matches (with a for loop, for example) , or simply use Array.prototype.find() :

login() {
  var correspondingUser = this.users.find(u => this.name == u.text && this.password == u.password);
  if (correspondingUser) { alert('Welcome, ' + correspondingUser.text); }
  else { alert('failed'); }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM