【VUE】vue+Verify实现防刷验证码验证

因为公司要做防刷,所以要验证码功能,于是又在网上找,看了一圈都是需要收费的,最后找了一个纯前端的开源,免费的验证码插件Verify,Verify的github地址: https://github.com/Hibear/verify,但是毕竟不需要后端配合,对安全性要求不高的可以安利一下

验证码效果图

验证码图片

Verify使用

Verify的资源包下载,注意使用时还要引入下载包中的images、fonts文件夹。

<!-- index.html -->
<head>
<script src="static/js/jquery.min.js"></script>
<script src="static/js/verify.min.js"></script>
</head>
<!-- main.js -->
import './assets/css/verify.css'   //验证码

为了方便使用,抽出来做组件mpanel.vue,并根据自己的需求改了验证码的样式

<!-- mpanel.vue -->
<template>
    <transition name="fade">
        <div class="modal-box">
            <div class="modal-content">
                <!--头部-->
                <div class="modal-header">
                    <p class="title">验证码验证</p>
                    <a @click="onCancel"
                       class="modal-close"
                       href="javascript:void(0)">
                        <x-icon type="ios-close"
                                size="30"></x-icon>
                    </a>
                </div>
                <!--内容区域-->
                <div class="modal-body">
                    <div id="mpanel"
                         ref="mpanel">
                    </div>
                  <div id="check-btn" class="verify-btn">确定</div>
                </div>
                <!--尾部,操作按钮  -->
                <!-- <div class="modal-footer">
                </div> -->
            </div>
        </div>
    </transition>

</template>

<script>
import { XDialog, TransferDomDirective as TransferDom } from 'vux'
export default {
    name: 'mpanel',
    data() {
        return {
            path: null
        }
    },
    mounted() {
        this.initMpanel();
    },
    methods: {
        onCancel() {
            this.$emit('close');
        },
        // 提示框
        showToolTip(text, timeout = 2000) {
            this.$vux.toast.text(text);
        },
        // 验证
        initMpanel() {
            this.codeVerify()  //运算验证码
            // this.slideVerify()  //拼图验证码
            // this.pointsVerify()  //拼字验证码
        },
        // 运算验证码
        codeVerify() {           // https://veui.net/document/index
            let _this = this
            $('#mpanel').codeVerify({
                type: 2,
                figure: 100,
                arith: 0,
                width: '100%',
                height: '50px',
                fontSize: '30px',
                btnId: 'check-btn',
                ready: function () {
                },
                success: function () {
                    _this.showToolTip("验证成功!")
                    // 向父组件传值
                    _this.$emit('success');
                },
                error: function () {
                    _this.showToolTip("验证码不匹配!")
                }
            });
        },
        // 拼图验证码
        slideVerify() {           // https://veui.net/document/index
            let _this = this
            $('#mpanel').slideVerify({
                type: 2,
                mode: 'pop',
                vOffset: 5,
                vSpace: 5,
                explain: '向右滑动完成验证',
                imgUrl: 'http://txh-cdn.96qbhy.com/',
                imgName: ['20181010170653M58v1KlH.jpg', '20181010170719McH7EkZK.jpg'],
                imgSize: {
                    width: '100%',
                    height: '200px',
                },
                blockSize: {
                    width: '40px',
                    height: '40px',
                },
                barSize: {
                    width: '100%',
                    height: '40px',
                },
                ready: function () {
                },
                success: function () {
                    _this.showToolTip("验证成功!")
                    // 向父组件传值
                    _this.$emit('success');
                },
                error: function () {
                    _this.showToolTip("验证码不匹配!")
                }
            });
        },
        // 拼字验证码
        pointsVerify() {           // https://veui.net/document/index
            let _this = this
            $('#mpanel').pointsVerify({
                mode: 'pop',
                defaultNum: 4,
                checkNum: 2,
                vSpace: 5,
                imgUrl: 'http://txh-cdn.96qbhy.com/',
                imgName: ['20181010170653M58v1KlH.jpg', '20181010170719McH7EkZK.jpg'],
                imgSize: {
                    width: '100%',
                    height: '200px',
                },
                barSize: {
                    width: '100%',
                    height: '40px',
                },
                ready: function () {
                },
                success: function () {
                    _this.showToolTip("验证成功!")
                    // 向父组件传值
                    _this.$emit('success');
                },
                error: function () {
                    _this.showToolTip("验证码不匹配!")
                }
            });
        }
    }
}
</script>
<style scoped>
.modal-box {
  position: fixed;
  display: flex;
  justify-content: center;
  align-items: center;
  left: 0;
  top: 0;
  z-index: 100;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}
.modal-content {
  position: relative;
  width: 300px;
  /* background: #fff; */
  border-radius: 10px;
  box-sizing: border-box;
  font-size: 13px;
}
.modal-header {
  text-align: center;
  border: 0;
}
.modal-header .title {
  font-size: 20px;
  font-weight: 550;
}
.modal-body{
    margin-top: -25px;
}
.modal-close {
  position: absolute;
  right: -10px;
  top: -15px;
  color: #999494;
  font-size: 14px;
}

.fade-enter-active {
  animation: fade-in 0.5s;
}
.fade-leave-active {
  animation: fade-in 0.5s reverse;
}
@keyframes fade-in {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.5);
  }
  100% {
    transform: scale(1);
  }
}
</style>

验证码组件引用

<!-- home.vue -->
</template>
...
    <!-- 验证码 start -->
    <mpanel v-if="mpanelShow"
            @close="mpanelShow = false"
            @success="onMpanelSuccess"></mpanel>
    <!-- 验证码 end -->
...
</template>
<script>
import Mpanel from 'Components/mpanel/mpanel'   //验证码
export default {
  data() {
    return {
      mpanelShow: false, //验证码是否显示
    }
  },
  methods: {
    // 是否要验证
    checkVerifyCodeApi(options) {
      checkVerifyCode(options).then(res => {
        if (res.data && res.data.code === 0) {
          //不要验证执行代码
        } else { 
          //需要验证码,弹窗显示
          this.mpanelShow = true;
        }
      })
    },
    // 验证通过
    onMpanelSuccess() {
      this.mpanelShow = false;
      //执行代码
    }
  }
}

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很抱歉,我作为AI语言模型无法提供完整的代码。但是,我可以给你提供一些思路和代码片段。 前端部分: 1. 注册页面代码: ``` <template> <div> <h2>注册</h2> <form> <div> <label>用户名:</label> <input type="text" v-model="username"> </div> <div> <label>密码:</label> <input type="password" v-model="password"> </div> <div> <label>确认密码:</label> <input type="password" v-model="confirmPassword"> </div> <button type="submit" @click.prevent="register">注册</button> </form> </div> </template> <script> export default { data() { return { username: '', password: '', confirmPassword: '' }; }, methods: { register() { // 发送注册请求 this.$http.post('/api/register', { username: this.username, password: this.password }).then(response => { if (response.data.code === 0) { alert('注册成功!'); this.$router.push('/login'); } else { alert(response.data.msg); } }).catch(error => { console.log(error); }); } } }; </script> ``` 2. 登录页面代码: ``` <template> <div> <h2>登录</h2> <form> <div> <label>用户名:</label> <input type="text" v-model="username"> </div> <div> <label>密码:</label> <input type="password" v-model="password"> </div> <button type="submit" @click.prevent="login">登录</button> </form> </div> </template> <script> export default { data() { return { username: '', password: '' }; }, methods: { login() { // 发送登录请求 this.$http.post('/api/login', { username: this.username, password: this.password }).then(response => { if (response.data.code === 0) { localStorage.setItem('token', response.data.token); alert('登录成功!'); this.$router.push('/'); } else { alert(response.data.msg); } }).catch(error => { console.log(error); }); } } }; </script> ``` 后端部分: 1. Flask 实现注册: ``` @app.route('/api/register', methods=['POST']) def register(): username = request.form.get('username') password = request.form.get('password') # 判断用户名是否已经被注册 user = User.query.filter_by(username=username).first() if user: return jsonify({'code': 1, 'msg': '用户名已存在!'}) # 插入新用户 user = User(username=username, password=generate_password_hash(password)) db.session.add(user) db.session.commit() return jsonify({'code': 0, 'msg': '注册成功!'}) ``` 2. Flask 实现登录: ``` @app.route('/api/login', methods=['POST']) def login(): username = request.form.get('username') password = request.form.get('password') # 判断用户是否存在 user = User.query.filter_by(username=username).first() if not user: return jsonify({'code': 1, 'msg': '用户名不存在!'}) # 验证密码是否正确 if not check_password_hash(user.password, password): return jsonify({'code': 2, 'msg': '密码错误!'}) # 生成 token token = generate_token(user.id) return jsonify({'code': 0, 'msg': '登录成功!', 'token': token}) ``` 3. Flask 实现 token 认证: ``` from flask_httpauth import HTTPTokenAuth auth = HTTPTokenAuth(scheme='Bearer') @auth.verify_token def verify_token(token): try: data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256']) g.user_id = data['id'] return True except: return False @app.route('/api/user_info') @auth.login_required def user_info(): user = User.query.filter_by(id=g.user_id).first() return jsonify({'username': user.username}) ``` 其中,`generate_token` 函数和 `check_password_hash` 函数需要自行实现。 数据库部分: ``` CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(100) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` 以上代码仅供参考,实际应用还需要根据具体需求做出相应修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值