密码强度计算属性应返回包含level、score、tips、colorclass四个字段的对象,其中level为"weak"/"medium"/"strong"字符串,score为0–100数字,tips为缺失项数组,colorclass为对应css类名。

用 Vue 的计算属性实现密码强度实时校验,核心是把校验逻辑封装进 computed,让它自动响应密码输入变化,并返回可直接用于模板的结构化结果(比如等级、得分、提示文案、颜色类名等)。
密码强度计算属性要返回什么
一个实用的计算属性不应只返回“强/中/弱”字符串,而应返回一组配套数据,方便模板灵活渲染:
-
level:字符串,如
"weak"、"medium"、"strong" - score:数字,0–100,便于做进度条或分级着色
-
tips:数组,列出当前缺失项,如
["至少8位", "需含大写字母"] -
colorClass:对应 CSS 类名,如
"strength-red"、"strength-green"
校验规则建议写成独立函数
把判断逻辑抽离为纯函数,提高可读性和复用性。例如:
function getPasswordStrength(password) {
let score = 0;
const tips = [];
if (password.length >= 8) score += 25;
else tips.push("长度至少8位");
if (/[a-z]/.test(password)) score += 25;
else tips.push("需含小写字母");
if (/[A-Z]/.test(password)) score += 25;
else tips.push("需含大写字母");
if (/\d/.test(password)) score += 15;
else tips.push("需含数字");
if (/[^A-Za-z0-9]/.test(password)) score += 10;
else tips.push("需含特殊字符");
const level = score >= 80 ? "strong" : score >= 60 ? "medium" : "weak";
const colorClass = { weak: "text-red-500", medium: "text-yellow-500", strong: "text-green-500" }[level];
return { score, level, tips, colorClass };
}
这个函数不依赖 Vue 实例,测试和维护都更简单。
在组件中使用计算属性调用它
在 Vue 组件的 computed 中调用该函数,并传入响应式密码字段:
export default {
data() {
return {
password: ""
};
},
computed: {
strengthInfo() {
return getPasswordStrength(this.password);
}
}
};
这样,只要 password 变,strengthInfo 就自动更新,无需手动触发或监听。
模板里直接绑定计算结果
利用返回的对象解构,让模板简洁清晰:
<input type="password" v-model="password"><div :class="strengthInfo.colorClass">
强度:{{ strengthInfo.level }}({{ strengthInfo.score }}/100)
</div>
- {{ tip }}
不需要额外的 watch 或事件处理,也不用在 methods 里反复调用验证函数——计算属性天然具备缓存与响应性。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











