javascript - 在 Vue/JS 中为条件重写几个 if 循环的更好方法是什么?
问题描述
我在 Vue JS 应用程序中有以下代码,我在其中尝试更改文本上的几个条件类,其中文本根据仪表的值更改颜色:
<span class="card__form__meter__warning" :class=" { weak : password_weak, 'very-weak' : password_veryweak, strong : password_strong, valid : password_verystrong } ">{{ password_warning }}</span>
以下代码有效,但我觉得这是一种可怕的、重复的方式来做一些可能更容易实现的事情:
data: {
name: null,
emailAddress: null,
password: null,
password_warning: 'Strong password required',
password_veryweak: false,
password_weak: false,
password_strong: false,
password_verystrong: false,
...
if (this.meter == 0) {
this.password_veryweak = false
this.password_warning = 'Strong password required'
}
if ( this.meter == 25) {
this.password_warning = 'Very weak (not strong enough)'
this.password_veryweak = true
this.password_weak = false
this.password_strong = false
this.password_verystrong = false
}
if (this.meter == 50 ) {
this.password_warning = 'Weak (not strong enough)'
this.password_weak = true
this.password_veryweak = false
this.password_strong = false
this.password_verystrong = false
}
if (this.meter == 75) {
this.password_warning = 'Strong'
this.password_strong = true
this.password_verystrong = false
this.password_weak = false
this.password_veryweak = false
}
if (this.meter > 75) {
this.password_warning = 'Very Strong'
this.password_verystrong = true
this.password_strong = false
this.password_weak = false
this.password_veryweak = false
}
当仪表值发生变化时,我在删除以前的条件类时遇到了真正的问题,因此我结束了设置
this.password_weak = false
this.password_strong = false
this.password_verystrong = false
对于每个条件。
我觉得我可能犯了一个非常基本的错误,因此我们非常感谢您提供任何帮助。
谢谢
- - -编辑 - - - -
computed: {
password_warning: function () {
if (this.meter == 0) {
this.password_class = ''
return 'Strong password required'
} else if (this.meter == 25) {
this.password_class = 'very-weak'
return 'Very weak (not strong enough)'
} else if (this.meter == 50) {
this.password_class = 'weak'
return 'weak (not strong enough)'
} else if (this.meter == 75) {
this.password_class = 'strong'
return 'Strong'
} else {
this.password_class = 'strong'
return 'Very strong'
}
},
}
解决方案
不要使用对象文字中的条件类。使用单个数据属性来存储您的类名并直接使用它:
<span class="card__form__meter__warning" :class="password_class">{{ password_warning }}</span>
设置代码this.password_class
变得非常简单。
我建议继续进行,甚至创建从值派生的password_class
计算password_warning
属性meter
,而不是强制分配它们。
推荐阅读
- embedded - 在 STM32CubeMX 生成的 USB 项目中设置 USB 设备名称
- python - Asterisk (raspbx): py 脚本 - 打开星号 CLI 并触发命令
- startup - 无法使用 IHostingEnvironment 获取路径
- frontend - 前端开发需要.net 门户?
- php - Codeigniter 控制器,升级后配置变量
- c# - 如何在 Unity 中使用rigidbody2d.velocity 跟随对象?
- angular - Angular 6:检测带有异步管道的表单是否有实际变化
- python - 从张量流中的张量返回k个最小元素
- c# - 动态调整图片框大小时的小问题(工具提示延迟,“闪烁”)
- c# - 不支持关键字:“元数据”。在杭火