首页 > 解决方案 > 使用 vue.js 和 js 获取数组

问题描述

vue 和 js 的新手。尝试创建一个简单的登录身份验证。'if' 适用于数组 [0] 但不适用于 [1][2][3] 等。我希望它检查所有数组是否匹配。

这是我的代码:

任何帮助将不胜感激。

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

    }

}); ```

标签: javascripthtmlvue.js

解决方案


首先,我希望您将其作为一种练习,只是为了自己,或者并不真正关心安全性。应始终在服务器端检查用户凭据。

话虽如此,您可以遍历用户,直到找到匹配的用户 for 例如,使用循环),或者简单地使用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'); }
}

推荐阅读