vue3生成隨機密碼的示例代碼
實現(xiàn)效果

實現(xiàn)思路
- 完成布局
- 完成生成隨機數(shù)的方法
- 完成生成隨機密碼的方法
完成布局
布局直接用element-plus組件庫里的el-from+checkbox完成一個簡單的表單布局即可。
完成生成隨機數(shù)的方法
這里我們要四種隨機數(shù),大寫字母、小寫字母、數(shù)字、特殊符號。這里實現(xiàn)有兩種方式。
第一種直接定義四個字符串,第一個字符串存所有的大寫字母、第二個字符串存所有的小寫字母、第三個所有的數(shù)字、第四個所有的特殊符號。
第二種使用Unicode編碼。將隨機數(shù)對應大寫字母、小寫字母、數(shù)字Unicode編碼的范圍取出對應的結(jié)果。 大寫字母是65-90、小寫字母是97-122,數(shù)字是48-57。
這兩種都要使用Math.floor(Math.random()) 獲取隨機數(shù)。我這里用第二種方法
完成生成隨機密碼的方法
定義一個數(shù)組對象。每個對象有funcName:對應隨機數(shù)方法名,label:左側(cè)標簽名,checked:選中狀態(tài)。循環(huán)密碼長度,每次增加選擇密碼種類數(shù)量,遍歷定義的數(shù)組對象,判斷是否是選中狀態(tài),如果是調(diào)用該種類的隨機方法,每次將返回的值拼接。循環(huán)完隨機密碼生成成功。
部分代碼
<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: '包括數(shù)字',
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>總結(jié)
- Math.floor、Math.random生成隨機數(shù)的使用
- unicode編碼、String.fromCharCode方法的使用
到此這篇關于vue3生成隨機密碼的示例代碼的文章就介紹到這了,更多相關vue3生成隨機密碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue 實現(xiàn)setInterval 創(chuàng)建和銷毀實例
這篇文章主要介紹了vue 實現(xiàn)setInterval 創(chuàng)建和銷毀實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
vue同一個瀏覽器登錄不同賬號數(shù)據(jù)覆蓋問題解決方案
同一個瀏覽器登錄不同賬號session一致,這就導致后面登錄的用戶數(shù)據(jù)會把前面登錄的用戶數(shù)據(jù)覆蓋掉,這個問題很常見,當前我這邊解決的就是同一個瀏覽器不同窗口只能登錄一個用戶,對vue同一個瀏覽器登錄不同賬號數(shù)據(jù)覆蓋問題解決方法感興趣的朋友一起看看吧2024-01-01
element-ui el-dialog嵌套table組件,ref問題及解決
這篇文章主要介紹了element-ui el-dialog嵌套table組件,ref問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02

