学习使用vue实现一个验证码(随机生成汉字,按顺序点击汉字以完成验证)

目录

写在前面:

主要实现以及主要功能:

实现效果展示:

 具体实现:

 html:

data:

methods:

watch:

两个钩子:

样式:


写在前面:

这种形式的验证码有的时候色彩过于丰富,也可能出现背景图片、文字背景等加载不好等状况,对某些使用者(对颜色辨别能力较差或缺少颜色辨别能力、年长人群等)可能不太友好。可能基于这些原因,我很少见到这种验证码(‾◡◝)o(* ̄▽ ̄*)ブ。

主要实现以及主要功能:

1、随机生成背景图片;

2、根据 utf-8(Unicode)中文编码的范围(u4e00 —— u9fa5)随机生成四个编码,再分别解码为汉字,覆盖在背景图片上方;

3、提示用户根据指定的汉字顺序依次点击层叠于背景图片上的汉字以完成验证;

4、根据用户对汉字的点击顺序,生成小于汉字大小的数字覆盖在点击位置以提示用户当前的点击顺序;

5、当用户再次点击已被点击的汉字,将取消当前汉字以及数字提示大于当前汉字的所有汉字的点击,使用户可以重新操作。(比如如用户根据主观判断依次点击了汉字 “一”、“二”、“三”,那么汉字 “一”、“二”、“三” 上方将分别出现数字提示图标①、②、③,当用户在未点击第四个汉字之前又点击了汉字“一”,其数字提示图标为①,那么大于等于数字1的图标将消失,大于等于数字图标1的操作将被撤销,所以用户的此次点击撤销了此前在本次验证中的所有点击,用户可以在本次验证中重新操作而不减少可验证次数)

6、当用户点击汉字个数达到四个,自动判断用户的验证是否通过。给予用户三次验证机会,每次验证失败弹出相应提示,显示一段时间后自动更新验证码;尝试三次都不成功则不可再操作;验证成功给予验证成功提示。在用户点击汉字验证阶段,用户可以更换(刷新)验证码。

实现效果展示:

 具体实现:

 html:

四个数字提示图标来源于网络,下载到了项目中的图片文件夹里

来源:https://www.iconfont.cn/      (阿里巴巴矢量图标库)

<template>
  <div class="outside" ref="outside">
    <div class="display-area" ref="content">
        <!-- 风景背景图 -->
        <img class="bg-picture" :src="background" alt="背景图片">
        <!-- 四个随机文字-->
        <span class="word-img" v-for="e of words" :key="e.index" :style="customStyle[e.index]" @click="choose(e.index,$event)">{{e.word}}</span>
        <!-- 点击汉字后贾昂出现提示数字小图标 -->
        <img class="number-tip" src="../assets/数字1.png" alt="1" v-show="choseOrder.length>=1" :style="numtip[0]" @click="withdrawChoose(0)">
        <img class="number-tip" src="../assets/数字2.png" alt="2" v-show="choseOrder.length>=2" :style="numtip[1]" @click="withdrawChoose(1)">
        <img class="number-tip" src="../assets/数字3.png" alt="3" v-show="choseOrder.length>=3" :style="numtip[2]" @click="withdrawChoose(2)">
        <img class="number-tip" src="../assets/数字4.png" alt="4" v-show="choseOrder.length>=4" :style="numtip[3]" @click="withdrawChoose(3)">
        
        <div v-show="isSucceed" class="tip">
            <div class="tip-content">验证成功!</div>
        </div>
    </div>
    
    <center>
        <div class="msg" v-show="!isSucceed">
            <p class="action-tip">请按顺序点击以下汉字以完成验证!</p>
            <!-- 打乱展示顺序 -->
            <p class="action-target">“{{words[correctOrder[0]].word}}”,“{{words[correctOrder[1]].word}}”,“{{words[correctOrder[2]].word}}”,“{{words[correctOrder[3]].word}}”</p>
            <button @click="changeAll()">换一张</button>
        </div>
    </center>
    
    <div v-show="falseTip && chance!=0" class="tip">
        <div class="tip-content">验证失败,请重新验证<br>剩余{{chance}}次机会</div>
    </div>
    <div v-show="chance===0" class="tip">
        <div class="tip-content">验证失败!</div>
    </div>
  </div>
</template>

data:

八张风景背景图来源于网络

data(){
        return{
            bgPictures:[
                {id:'0',src:'https://img2.baidu.com/it/u=1381481047,1529970259&fm=253&fmt=auto&app=138&f=JPEG?w=752&h=500'},
                {id:'1',src:'https://img2.baidu.com/it/u=4286724097,1475456570&fm=253&fmt=auto&app=120&f=JPEG?w=889&h=500'},
                {id:'2',src:'https://img1.baidu.com/it/u=2310170655,486191485&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281'},
                {id:'3',src:'https://img2.baidu.com/it/u=2526401426,2132302010&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281'},
                {id:'4',src:'https://img2.baidu.com/it/u=2279721922,3725358742&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500'},
                {id:'5',src:'https://img1.baidu.com/it/u=2605372625,2257936617&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=313'},
                {id:'6',src:'https://img2.baidu.com/it/u=188805366,3528195373&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=675'},
                {id:'7',src:'https://img0.baidu.com/it/u=381886100,3541087750&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281'},
                {id:'8',src:'https://img2.baidu.com/it/u=769068768,1914010451&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500'}
            ],
            background:"",
            codeCharacter:[0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'],        //16进制数
            words:new Array(4),                                                 //储存四个汉字
            customStyle:[],                                                     //四个汉字的样式
            correctOrder:[],                                                    //正确的顺序
            choseOrder:[],                                                      //用户选择的顺序
            numtip:[],                                                          //数字的样式  用于提示用户点击了那个汉字的次序
            chance:3,                                                           //用户还可以尝试的次数
            falseTip:false,                                                     //用户验证失败,但是仍有次数,自动刷新时的提示
            isSucceed:false,                                                    //用户验证成功
        }
    },

methods:


unescape() 可以解码,被声明弃用了,但是还能用;

decodeURI()解码不了形如 %u4e00 的编码;汉字一般占三个字符,encodeURI()将汉字编码成三个“ %xxx ”连接的形式, 如汉字中使用encodeURI()被编码为:%E4%B8%AD,此种形式才能被 decodeURI() 解码。
           
范围:%u 4e00 - %u 9fa5  ,(有规律可循,因此可以随机生成汉字);
每一个文字都用类似于 %u4e00 这样规则的字符串进行编码,前两个字符 %u 是固定前缀;
第三个字符范围4-9;
当第三个字符取4,第四个字符范围e-f,其他情况范围0-f,往后位置在范围内任意取;
当第三个字符取9,第四个字符取f,第五个字符范围0-a,其他情况范围0-f;
当地三个字符取9,第四个字符取f,第五个字符取a,第六个字符范围0-5;
参考:https://wenku.baidu.com/view/3630b3f2c2c708a1284ac850ad02de80d4d8062d.html
 

    methods:{
        //随机选择四个文字,加入到 words 数组
        chooseFourWords(){
            let arr=new Array();

            for(let i=0;i<4;i++){
                let tempStr='%u';

                // 随机选择第三位字符
                let temp_3=4+Math.round(Math.random()*5);
                tempStr+=this.codeCharacter[temp_3];

                //随机选择第四位字符
                let temp_4;
                if(temp_3===4){
                    temp_4=14+Math.round(Math.random());
                }else{
                    temp_4=Math.round(Math.random()*15);
                }
                tempStr+=this.codeCharacter[temp_4];

                //随机选择第五位字符
                let temp_5;
                if(temp_4===15 && temp_3===9){
                    temp_5=Math.round(Math.random()*10);
                }else{
                    temp_5=Math.round(Math.random()*15);
                }
                tempStr+=this.codeCharacter[temp_5];

                //随机选择第六个字符
                let temp_6;
                if(temp_3===9 && temp_4===15 && temp_5===10){
                    temp_6=Math.round(Math.random()*5);
                }else{
                    temp_6=Math.round(Math.random()*15);
                }
                tempStr+=this.codeCharacter[temp_6];                

                arr.push({index:i,word:unescape(tempStr)});
            }

            this.words=arr;
        },
        //将平面图分成四个区域,左上,左下,右上,右下;参数可以是 0,1,2,3其一 分别设置左上,右上,左下,右下 区域
        //返回一个内联样式对象
        changeWordsStyle(area){
            if(Math.round(area)<0 || Math.round(area)>4 ){
                return undefined;
            }

            let halfWidth=this.$refs.content.offsetWidth / 2;
            let halfHeight=this.$refs.content.offsetHeight / 2;

            let right;
            let left;
            let top;
            let bottom;

            if(area===0 || area===2){
                right=halfWidth+(halfWidth-30)*Math.random()+'px';
            }else{
                left=halfWidth+(halfWidth-30)*Math.random()+'px';
            }

            if(area===2 || area===3){
                top=(halfHeight-5)*Math.random()+'px';
            }else{
                bottom=(halfHeight-5)*Math.random()+'px';
            }

            let rotate='rotate('+(30+Math.random()*(-60))+'deg)';
            let rotateX='rotateX('+(15+Math.random()*(-30))+'deg)';
            let rotateY='rotateY('+(15+Math.random()*(-30))+'deg)';
            let scale='scale('+(0.6+Math.random())+','+(0.6+Math.random())+')';

            return {left,top,right,bottom,transform:rotate+" "+rotateX+" "+rotateY+" "+scale,maxWidth:'70px',maxHeight:'80px'};
        },
        //更换背景图片
        chooseBGP(){
            return this.bgPictures[Math.round(Math.random()*8)].src;
        },
        //换一张    重新部署
        changeAll(){
            this.chooseFourWords();
            this.customStyle=[];
            for(let i=0;i<4;i++){
                this.customStyle.unshift(this.changeWordsStyle(3-i));
            }
            this.setCorrectOrder();
            this.background=this.chooseBGP();
            this.numtip=[];
            this.choseOrder=[];
        },
        //随机确定正确的点击顺序
        setCorrectOrder(){
            let s=new Set();                    //用集合来判断有没有重复
            while(s.size<4){
                s.add(Math.round(Math.random()*3));
            }
            this.correctOrder=[...s];
        },
        // 用户点击汉字标签 添加或撤回     第一个参数为点击汉字在words中的index标识
        choose(index,e){
            let temp=this.choseOrder.indexOf(index);
            if(temp===-1){              //在choseOrder中找不到即是添加
                this.choseOrder.push(index);
                this.numtip.push({left:e.clientX+'px',top:e.clientY+'px'});
            }else{                      //找得到即撤回自身以及上级所选(大于等于前数字标签的撤回,可重选)
                this.choseOrder.splice(temp);
                this.numtip.splice(temp);
            }
        },
        // 点击到提示数字 撤回
        withdrawChoose(index){
            this.choseOrder.splice(index);
            this.numtip.splice(index);
        }
    },

watch:

监视 choseOrder 数组,其按顺序储存用户点击的数据,当其长度等于 correctOrder 数组的长度,即四个汉字的长度4,则表示用户完成当前的验证操作,立即开始检查验证是否通过。

    watch:{
        choseOrder:{
            deep:true,
            handler(newval){
                //当用choseOrder的长度等于correctOrder的长度时,用户选择完毕,自动判断是否通过
                if(newval.length===this.correctOrder.length){
                    let succeed=true;
                    for(let i=0;i<this.correctOrder.length;i++){        //逐个判断
                        if(newval[i]!=this.correctOrder[i]){
                            succeed=false;
                        }
                    }
                    if(succeed){
                        this.isSucceed=true;
                        this.$refs.outside.style.border="0px";            //去除外边框
                    }else{
                        this.falseTip=true;                               //显示验证失败提示
                        this.chance--;                                    //可尝试机会减少
                        if(this.chance>0){                                //重新部署
                            setTimeout(()=>{
                                this.changeAll();
                                this.falseTip=false;
                            },1500)
                        }
                    }
                }
            }
        }
    },

两个钩子:

    beforeMount(){
        this.chooseFourWords();
        this.setCorrectOrder();
    },
    mounted(){
        for(let i=0;i<4;i++){
            this.customStyle.unshift(this.changeWordsStyle(3-i));
        }
        this.background=this.chooseBGP();
    }

样式:

在这里主要是用绝对定位加 z-index 属性来实现层叠和覆盖的,也可以使用 float 和 index 来做

    /* 最外侧轮廓 */
    .outside{
        width:400px;
        height:380px;
        border:1px solid black;
        position: absolute;
    }
    /**上方图片展示区域 */
    .display-area{
        width:100%;
        height: 75%;
        position: absolute;
        overflow: hidden;
    }
    .bg-picture{
        width: 100%;
        height: 100%;
        z-index: 2;
    }
    /**汉字span */
    .word-img{
        display: inline-block;
        box-sizing: border-box;
        padding:0.1em;        
        font-size: 2rem;
        font-weight: 700;
        border-radius: 0.3em;
        background:-webkit-gradient(linear, 0 0, 0 bottom, from(rgba(241, 210, 240, 0.644)), to(rgba(0, 0, 255, 0)));
        position: absolute;
        z-index: 4;
    }
    /**底部提示用户操作区 换一张按钮放置区 */
    .msg{
        position: absolute;
        bottom: 8px;
        width:100%;
        z-index: 8;
    }
    p{
        margin-top: 0px;
        margin-bottom: 0px;
    }
    .action-target{
        font-size: 1.3em;
        line-height: 1.6;
    }
    button{
        background-image: linear-gradient(to right, #E0EAFC 0%, #CFDEF3  51%, #E0EAFC  100%);
        text-align: center;
        width: 5rem;
        height: 2rem;
        text-transform: uppercase;
        background-size: 200% auto;
        box-shadow: 0 0 20px #eee;
        border-radius: 10px;
        display: block;
    }
    /**数字顺序提示 */
    .number-tip{
        width:1.3rem;
        height: 1.3rem;
        background-color: #fff;
        border-radius: 90px;
        opacity: 0.9;
        z-index:8;
        position: fixed;
    }
    .word-img,button,.number-tip:hover{
        cursor: pointer;
    }
    /**判断用户验证结果的提示 */
    .tip{
        position: absolute;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        background-color: rgba(128, 127, 127,0.8);
        font-size: large;
        z-index: 10;
    }
    .tip-content{
        position: absolute;
        left: 50%;
        top:50%;
        transform: translate(-50%,-50%);
        font-size: 2rem;
        font-weight: bolder;
        z-index:15;
    }

  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
### 回答1: 好的,下面是使用Vue生成一个移动端登录页,包含账号、密码以及验证码的示例代码: ```html <template> <div class="login"> <h1>用户登录</h1> <form> <div class="form-group"> <label for="username">账号:</label> <input type="text" id="username" v-model="username" required> </div> <div class="form-group"> <label for="password">密码:</label> <input type="password" id="password" v-model="password" required> </div> <div class="form-group"> <label for="verify-code">验证码:</label> <input type="text" id="verify-code" v-model="verifyCode" required> <img :src="verifyCodeImg" alt="验证码" @click="refreshVerifyCode"> </div> <button type="submit" @click.prevent="submit">登录</button> </form> </div> </template> <script> export default { data() { return { username: '', password: '', verifyCode: '', verifyCodeImg: '/api/getVerifyCode', // 获取验证码图片的接口地址 }; }, methods: { refreshVerifyCode() { // 刷新验证码图片 this.verifyCodeImg = '/api/getVerifyCode?' + Date.now(); }, submit() { // 提交表单数据 // 可以通过axios等库向后端发送登录请求 console.log(this.username, this.password, this.verifyCode); }, }, }; </script> <style> /* 样式可以根据自己的需求进行调整 */ .login { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; flex-direction: column; } h1 { font-size: 24px; margin-bottom: 30px; } form { display: flex; flex-direction: column; align-items: center; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 5px; font-size: 16px; } input[type="text"], input[type="password"] { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; font-size: 16px; } button[type="submit"] { margin-top: 30px; padding: 10px 20px; background-color: #007aff; color: #fff; border: none; border-radius: 4px; font-size: 16px; } </style> ``` 这个示例代码中使用Vue的单文件组件,包括一个表单和相关的数据和方法。其中,账号和密码输入框使用了`type="text"`和`type="password"`,验证码输入框使用了`type="text"`。验证码图片的地址可以通过后端接口获取,每次刷新图片时可以在地址后面加一个随机数避免缓存。提交表单数据的方法可以使用axios等库向后端发送登录请求。 ### 回答2: 使用Vue生成一个移动端登录页面相对简单。以下是一个简单的实例: 1. 首先,确保你已经安装了Vue框架。在终端中使用npm或yarn安装Vue:npm install vue 或 yarn add vue 2. 在你的项目中创建一个新的vue组件,例如Login.vue。 3. 在Login.vue文件中,使用template标签添加HTML代码,以展示登录表单。例如: ```html <template> <div> <form> <label for="username">账号:</label> <input type="text" id="username" v-model="username"> <br> <label for="password">密码:</label> <input type="password" id="password" v-model="password"> <br> <label for="captcha">验证码:</label> <input type="text" id="captcha" v-model="captcha"> <img src="captcha.jpg" alt="验证码图片"><!-- 假设有一个验证码图片,可以点击刷新 --> <br> <button type="submit" @click="login">登录</button> </form> </div> </template> ``` 4. 在script标签中,定义和处理表单数据。例如: ```javascript <script> export default { data() { return { username: '', password: '', captcha: '' } }, methods: { login() { // 在这里可以添加发送登录请求的逻辑 // 可以使用this.username、this.password和this.captcha来获取输入的值 } } } </script> ``` 5. 最后,在应用的入口文件(例如main.js)中导入Login.vue组件: ```javascript import Vue from 'vue'; import Login from './Login.vue'; new Vue({ render: h => h(Login), }).$mount('#app'); ``` 这只是一个基本的示例,你可以根据自己的需求进行修改和扩展。记得添加必要的样式和样式类来适配移动端界面。 ### 回答3: Vue是一种用于构建用户界面的JavaScript框架,可以快速开发响应式移动端应用程序。下面是一个使用Vue生成移动端登录页的示例: 首先,我们需要安装Vue和一些相关的插件。可以使用npm或者yarn来安装这些工具。在终端中运行以下命令: ``` npm install vue npm install vue-router npm install vue-i18n ``` 接下来,创建一个Vue的实例并定义一个登录组件。 main.js文件: ```javascript import Vue from "vue"; import VueRouter from "vue-router"; import VueI18n from "vue-i18n"; import App from "./App.vue"; Vue.use(VueRouter); Vue.use(VueI18n); const router = new VueRouter({ routes: [ { path: "/", component: LoginComponent, }, ], }); const i18n = new VueI18n({ locale: "en", }); new Vue({ router, i18n, render: (h) => h(App), }).$mount("#app"); ``` App.vue文件: ```html <template> <div> <router-view></router-view> </div> </template> <script> export default { name: "App", }; </script> ``` LoginComponent.vue文件: ```html <template> <div> <input v-model="account" type="text" placeholder="请输入账号" /> <input v-model="password" type="password" placeholder="请输入密码" /> <input v-model="captcha" type="text" placeholder="请输入验证码" /> <button @click="login">登录</button> </div> </template> <script> export default { name: "LoginComponent", data() { return { account: "", password: "", captcha: "", } }, methods: { login() { // 验证账号密码和验证码,并执行登录逻辑 }, }, }; </script> ``` 最后,在index.html文件中添加一个id为"app"的div元素: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Page</title> </head> <body> <div id="app"></div> <script src="dist/build.js"></script> </body> </html> ``` 现在,你可以通过在终端中运行`npm run build`来构建项目,并在浏览器中打开index.html文件,就可以看到一个包含账号、密码和验证码的移动端登录页面了。 这个示例中的登录组件使用Vue的双向数据绑定(v-model)来实现输入框的数据绑定,然后通过按钮点击事件来触发登录逻辑。你可以根据自己的需求对其进行扩展和美化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bodyHealthy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值