实现效果

实现思路
- 完成布局
- 完成生成随机数的方法
- 完成生成随机密码的方法
完成布局
布局直接用element-plus组件库里的el-from+checkbox完成一个简单的表单布局即可。
完成生成随机数的方法
这里我们要四种随机数,大写字母、小写字母、数字、特殊符号。这里实现有两种方式。
第一种直接定义四个字符串,第一个字符串存所有的大写字母、第二个字符串存所有的小写字母、第三个所有的数字、第四个所有的特殊符号。
第二种使用Unicode编码。将随机数对应大写字母、小写字母、数字Unicode编码的范围取出对应的结果。 大写字母是65-90、小写字母是97-122,数字是48-57。
这两种都要使用Math.floor(Math.random()) 获取随机数。我这里用第二种方法
完成生成随机密码的方法
定义一个数组对象。每个对象有funcName:对应随机数方法名,label:左侧标签名,checked:选中状态。循环密码长度,每次增加选择密码种类数量,遍历定义的数组对象,判断是否是选中状态,如果是调用该种类的随机方法,每次将返回的值拼接。循环完随机密码生成成功。
部分代码
- <script>
- import { reactive, toRefs } from "vue";
- export default {
- components: {},
- setup() {
- const state = reactive({
- form: {
- padLength: 8
- },
- typeList: [
- {
- id: 1,
- funcName:'IsUpper',
- label: '包括大写字母',
- checked: true
- },
- {
- id: 2,
- funcName:'IsLower',
- label: '包括小写字母',
- checked: true
- },
- {
- id: 3,
- funcName:'Isnumber',
- label: '包括数字',
- checked: true
- },
- {
- id: 4,
- funcName:'IsCharacter',
- label:'包括符号',
- checked: true
- }
- ],
- password: ''
- });
- const getRandomLower = () => {
- return String.fromCharCode(Math.floor(Math.random() * 26) + 97)
- }
- const getRandomUpper = () => {
- return String.fromCharCode(Math.floor(Math.random() * 26) + 65)
- }
- const getRandomNumber = () => {
- return String.fromCharCode(Math.floor(Math.random() * 10) + 48)
- }
- const getRandomCharacter = () => {
- const characters = '!@#$%^&*(){}[]=<>/,.'
- return characters[Math.floor(Math.random() * characters.length)]
- }
- let randomFunc = {
- IsUpper: getRandomUpper,
- IsLower: getRandomLower,
- Isnumber: getRandomNumber,
- IsCharacter: getRandomCharacter
- }
- const getPassword = () => {
- state.password = ''
- let typesCount = 0
- state.typeList.forEach(v=>{
- typesCount += v.checked
- })
- if(typesCount === 0) {
- state.password = ''
- }
-
- for(let i = 0; i < state.form.padLength; i += typesCount) {
- state.typeList.forEach(item => {
- if(item.checked){
- state.password += randomFunc[item.funcName]()
- }
- })
- }
-
- }
-
- return {
- ...toRefs(state),
- getRandomLower,
- getRandomUpper,
- getRandomNumber,
- getRandomCharacter,
- getPassword
- };
- },
- };
- </script>
总结
- Math.floor、Math.random生成随机数的使用
- unicode编码、String.fromCharCode方法的使用
到此这篇关于vue3生成随机密码的示例代码的文章就介绍到这了,更多相关vue3生成随机密码内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!