Calv
Calv

Reputation: 125

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");
        }

    }

}); ```

Upvotes: 2

Views: 53

Answers (1)

blex
blex

Reputation: 25634

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'); }
}

Upvotes: 3

Related Questions