javascript - 使用 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");
}
}
}); ```
解决方案
首先,我希望您将其作为一种练习,只是为了自己,或者并不真正关心安全性。应始终在服务器端检查用户凭据。
话虽如此,您可以遍历用户,直到找到匹配的用户( 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'); }
}
推荐阅读
- bamboo - 为 Atlassian Bamboo 中的跑步设置“标志”
- python - 匹配内容创建新列
- http - 非 OPTIONS 响应中的“Access-Control-Allow-Origin: *”是一个漏洞吗?
- rest - 是否可以使用 splunk dbxquery 运行 curl 命令?
- python - 重复使用对齐的图像进行边缘检测和阈值处理
- amazon-web-services - 放大配置
- javascript - 如何从第二个下拉值中从数据库中获取数据
- javascript - KendoUI - 选择时禁用某些节点
- binding - 如何在 SwiftUI(或替代方法)的主体方法中初始化派生变量
- sql - 如何创建一个将记录从一个表插入到另一个表并检查有效性的过程?PL/SQL