vue3生成随机密码
时间: 2023-12-05 16:40:54 浏览: 197
生成随机密码
3星 · 编辑精心推荐
以下是一个使用Vue3和Element Plus制作的随机密码生成器的示例代码:
```html
<template>
<div class="password-generator">
<el-form :model="form" :rules="rules" ref="form" label-width="100px">
<el-form-item label="密码长度" prop="length">
<el-input-number v-model="form.length" :min="6" :max="20" :step="1"></el-input-number>
</el-form-item>
<el-form-item label="包含数字" prop="hasNumber">
<el-switch v-model="form.hasNumber"></el-switch>
</el-form-item>
<el-form-item label="包含小写字母" prop="hasLowercase">
<el-switch v-model="form.hasLowercase"></el-switch>
</el-form-item>
<el-form-item label="包含大写字母" prop="hasUppercase">
<el-switch v-model="form.hasUppercase"></el-switch>
</el-form-item>
<el-form-item label="包含特殊字符" prop="hasSpecial">
<el-switch v-model="form.hasSpecial"></el-switch>
</el-form-item>
<el-form-item label="生成密码" prop="password">
<el-input v-model="form.password" readonly></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="generatePassword">生成密码</el-button>
<el-button type="primary" @click="fillInPwd">填充密码</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import { ref } from 'vue'
import { useForm } from '@ant-design-vue/use'
export default {
setup() {
const { form, resetFields } = useForm({
length: 8,
hasNumber: true,
hasLowercase: true,
hasUppercase: true,
hasSpecial: false,
password: ''
})
const rules = {
length: [
{ required: true, message: '请输入密码长度', trigger: 'blur' },
{ type: 'number', message: '密码长度必须为数字值', trigger: 'blur' }
]
}
const generatePassword = () => {
const numbers = '0123456789'
const lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz'
const uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const specialCharacters = '!@#$%^&*()_+-=[]{}|;:,.<>?'
let characters = ''
let password = ''
if (form.hasNumber) {
characters += numbers
}
if (form.hasLowercase) {
characters += lowercaseLetters
}
if (form.hasUppercase) {
characters += uppercaseLetters
}
if (form.hasSpecial) {
characters += specialCharacters
}
for (let i = 0; i < form.length; i++) {
password += characters.charAt(Math.floor(Math.random() * characters.length))
}
form.password = password
}
const fillInPwd = () => {
const { setFieldsValue } = this.$refs.form
setFieldsValue({ password: form.password })
}
return {
form,
rules,
generatePassword,
fillInPwd
}
}
}
</script>
```
在这个示例中,我们使用了Vue3和Element Plus来创建一个随机密码生成器。用户可以选择密码的长度以及是否包含数字、小写字母、大写字母和特殊字符。点击“生成密码”按钮后,随机生成一个符合要求的密码,并显示在“生成密码”输入框中。用户可以点击“填充密码”按钮,将生成的密码填充到对应的密码框中。
阅读全文