本文将从多个方面介绍如何在eladmin中设置以数字为中心的验证码,以保证网站的安全性。
一、安装插件
要使用验证码,在eladmin中需要安装相关的插件。首先,在eladmin项目根目录下的package.json文件中添加以下依赖:
"vue-countdown-timer": "^1.0.1"
同时,使用以下命令安装依赖:
npm install vue-countdown-timer --save
二、编写验证码组件
在eladmin中,可以创建名为Captcha.vue的组件,其中包含以下代码:
<template> <div> <input type="text" v-model="code" :maxlength="codeLength" placeholder="请输入验证码"> <vue-countdown-timer ref="timer" :time="time" @on-timer-start="timerStarted" @on-timer-countdown="timerCountdown" @on-timer-end="timerEnded"></vue-countdown-timer> <button :disabled="timerStatus !== 'Init' || isCountdown" @click="getCode">{{buttonText}} </div> </template> <script> import VueCountdownTimer from 'vue-countdown-timer'; export default { name: 'Captcha', components: { VueCountdownTimer }, data() { return { code: '', codeLength: 4, // 默认验证码长度为4 time: 60, // 默认倒计时为60秒 timerStatus: 'Init', // 倒计时状态:Init/Start/Pause/Ended isCountdown: false, // 是否在倒计时 }; }, computed: { buttonText() { if (this.isCountdown) { return `重新发送(${this.$refs.timer.currentSecondsLeft}s)`; } return '获取验证码'; }, }, methods: { getCode() { // 发送请求获取验证码 // this.$http.post('/api/v1/captcha').then(response => { // console.log(response.data); // }).catch(error => { // console.log(error); // }); // 设置倒计时状态 if (this.timerStatus === 'Init' || this.timerStatus === 'Ended') { this.$refs.timer.start(); this.timerStatus = 'Start'; } else if (this.timerStatus === 'Pause') { this.$refs.timer.resume(); this.timerStatus = 'Start'; } }, timerStarted() { this.isCountdown = true; }, timerCountdown(currentSecondsLeft) { // 倒计时中的回调函数 }, timerEnded() { this.isCountdown = false; this.timerStatus = 'Ended'; }, }, }; </script>
三、在登录页面使用验证码
可以在登录页面中引入Captcha组件,并判断验证码是否正确。
<template> <div> <input type="text" v-model="username" placeholder="请输入用户名"> <input type="password" v-model="password" placeholder="请输入密码"> <Captcha ref="captcha"></Captcha> <button @click="login">登录</button> </div> </template> <script> import Captcha from '@/components/common/Captcha'; export default { name: 'Login', components: { Captcha }, data() { return { username: '', password: '', }; }, methods: { login() { // 判断验证码是否正确 if (this.$refs.captcha.code === '') { this.$message.error('请输入验证码!'); return; } // 发送请求进行登录 // this.$http.post('/api/v1/login', { // username: this.username, // password: this.password, // code: this.$refs.captcha.code, // }).then(response => { // console.log(response.data); // this.$message.success('登录成功!'); // }).catch(error => { // console.log(error); // this.$message.error('登录失败!'); // }); }, }, }; </script>
四、小结
以上就是如何在eladmin中设置以数字为中心的验证码的详细步骤。通过安装插件、编写验证码组件并在登录页面使用,可以防止暴力破解密码等安全问题。