精华内容
下载资源
问答
  • vue登录验证

    千次阅读 2018-03-27 20:43:11
    思路:前端验证1、路由meta中保存...// },2、使用vue-router的全局前置守卫进入路由前判断该路由是否需要登录验证router.beforeEach((to,from,next)=>{ if(to.meta.requireAuth){ //是否需要登录权限 ......

    思路:

    前端验证

    1、路由meta中保存是否需认证字段

    //   meta:{
    //     requireAuth:true //需要登录验证
    //   },

    2、使用vue-router的全局前置守卫进入路由前判断该路由是否需要登录验证

    router.beforeEach((to,from,next)=>{
      if(to.meta.requireAuth){ //是否需要登录权限
        ...
      }else{
        next();
      }
    });

    3、获取缓存(这里使用store)中是否有token字段没有则跳转至登录页面并保存当前请求路径

    if(store.state.token){
          next()
        }else{
          next({
            path:'/login',
            query:{redirect:to.fullPath}
          })
        }

    4、为处理刷新页面store中数据清除导致每次都得重新登录可以在保存token至store中同时保存一份至localstorage中

    new Vuex.Store({
        state: {
            token: null,
          },
          mutations: {
            login: (state,data)=> {
                localStorage.token=data
                state.token=data
            },
            logout: (state,data)=> {
                localStorage.removeItem('token')
                state.token=null
              }
          }
    })
    5、刷新页面时获取token赋值到store中
    //页面刷新,重新设置token
    if(window.localStorage.getItem('token')){
      store.commit(types.LOGIN,window.localStorage.getItem('token'))
    }

    后端验证

    1、使用axios请求拦截器在发送请求前判断是否有token有则添加到请求头中无则跳转至登录页面

    axios.interceptors.request.use(
        config => {
            if (store.state.token) {  // 判断是否存在token,如果存在的话,则每个http header都加上token
                config.headers.Authorization = `token ${store.state.token}`;
            }
            return config;
        },
        err => {
            return Promise.reject(err);
        });

    2、使用axios响应拦截器获取响应前判断token是否失效

    axios.interceptors.response.use(
        response => {
            return response;
        },
        error => {
            if (error.response) {
                switch (error.response.status) {
                    case 401:
                        // 返回 401 清除token信息并跳转到登录页面
                        store.commit(types.logout);
                        router.replace({
                            path: 'login',
                            query: {redirect: router.currentRoute.fullPath}
                        })
                }
            }
            return Promise.reject(error.response.data)   // 返回接口返回的错误信息
        });

    展开全文
  • 本篇文章主要介绍了Vue实战之vue登录的实现代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • 首先给文本框设置 type=“number” 属性 <div class="layui-fulid" id="house-login" >...手机号登录</p> <div class="layui-input-block login"> <i class="layui-icon layui-icon-house-mob

    首先给文本框设置 type=“number” 属性

        <div class="layui-fulid" id="house-login" >
          <div class="layui-form">
            <p>手机号登录</p>
            <div class="layui-input-block login">
              <i class="layui-icon layui-icon-house-mobile"></i>
              <input type="number" required lay-verify="required"  placeholder="请输入手机号"  v-model="loginForm.phone"   @input="handerInput" class="layui-input">
            </div>
            <div class="layui-input-block getCode">
              <input type="number" required lay-verify="required"   placeholder="请输入短信验证码" v-model="loginForm.code"  class="layui-input">
              <button class="layui-btn" @click="getCode">获取验证码</button>
            </div>
            <button class="layui-btn"  lay-submit lay-filter="user-login" @click="login" @keyup.enter="keyDown">登录</button>
          </div>
        </div>
    

    methods中判断输入的内容

     data(){
          return {
            loginForm:{
              phone:"",
              code:""
            },
          }
        },
        methods:{
    
        //获取验证码
        getCode(){
          //判断手机号码是否正确
         if (this.loginForm.phone.length <= 0) {
            this.$message.error("请输入手机号");
          }else if(!(/^1[3-9][0-9]\d{8}$/.test(this.loginForm.phone))){
            this.$message.error("请输入正确手机号");
          }
          //发起请求
          getCode(this.loginForm.phone).then(res=>{
            if(res.data.code!=200){
              this.$message.error("获取验证码失败,请检查手机号码是否正确")
            }
          })
    
        },
        //登录
        login(){
          //发起请求
          login(this.loginForm).then(res=>{
            if(res.data.code==200){
              localStorage.setItem("token",res.data.data);
              this.$message.success("登录成功")
              //跳转首页
              this.$router.push('/ProductList');
            }
          })
        },
        keyDown(e){
          //如果是回车则执行登录方法
          if(e.keyCode == 13){
            //需要执行的方法
            this.login();
          }
        },
        // 判断自定义输入事件去掉 type="number 的  .
        handerInput() {
          // 判断不能输入小数点
          let str = '' + this.loginForm.phone;
          if (str.indexOf('.') !== -1) {
            let arr = str.split('');
            arr.splice(arr.length - 1);
            let str2 = arr.join('');
            this.loginForm.phone = +str2;
          }
        },
      },
       mounted () {
        //绑定事件
        window.addEventListener('keydown',this.keyDown);
      },
      //销毁事件
      destroyed(){
        window.removeEventListener('keydown',this.keyDown,false);
      },
    

    去掉 type="number 上下箭头

    <style scoped>
    
      input[type=number] {
        -moz-appearance:textfield;
      }
      input[type=number]::-webkit-inner-spin-button,
      input[type=number]::-webkit-outer-spin-button {
        -webkit-appearance: none;
        margin: 0;
      }
    </style>
    
    展开全文
  • Vue 登录验证之滑动拼图验证码

    千次阅读 2019-09-18 07:39:13
    登录时实现滑动登录验证需要一些步骤: 弹窗功能 弹窗基于元素定位 元素拖动 canvas绘图 基础逻辑 1. 弹窗和弹窗组件 使用elementUI的el-popover组件,可以看elementUI官网的说明。 2. Canvas绘制图片 canvas...

    滑动登录验证码

    登录验证码
    登录时实现滑动登录验证需要一些步骤:

    1. 弹窗功能
    2. 弹窗基于元素定位
    3. 元素拖动
    4. canvas绘图
    5. 基础逻辑

    1. 弹窗和弹窗组件

    使用elementUI的el-popover组件,可以看elementUI官网的说明。

    2. Canvas绘制图片

    • canvas绘制外部img图片

    代码:

    let mainDom = document.querySelector("#codeImg");
    let bg = mainDom.getContext("2d");
    let width = mainDom.width;
    let height = mainDom.height;
    let blockDom = document.querySelector("#sliderBlock");
    let block = blockDom.getContext("2d");
    //重新赋值,让canvas进行重新绘制
    blockDom.height = height;
    mainDom.height = height;
    let imgsrc = require("../assets/images/back.jpg");
    let img = document.createElement("img");
    img.style.objectFit = "scale-down";
    img.src = imgsrc;
    img.onload = function() {
     bg.drawImage(img, 0, 0, width, height);
     block.drawImage(img, 0, 0, width, height);
    };
    

    绘制两个canvas,一个是背景一个是滑块

    重点在

    let mainDom = document.querySelector("#codeImg");
    let imgsrc = require("../assets/images/back.jpg");
    let bg = mainDom.getContext("2d");
    let img = document.createElement("img");
    img.onload = function() {
     bg.drawImage(img, 0, 0, width, height);
    };
    
    • canvas绘制滑块部分

    滑动拼图验证码
    代码:

    drawBlock(ctx, xy = { x: 254, y: 109, r: 9 }, type) {
     let x = xy.x,
     y = xy.y,
     r = xy.r,
     w = 40;
     let PI = Math.PI;
     //绘制
     ctx.beginPath();
     //left
     ctx.moveTo(x, y);
     //top
     ctx.arc(x + (w + 5) / 2, y, r, -PI, 0, true);
     ctx.lineTo(x + w + 5, y);
     //right
     ctx.arc(x + w + 5, y + w / 2, r, 1.5 * PI, 0.5 * PI, false);
     ctx.lineTo(x + w + 5, y + w);
     //bottom
     ctx.arc(x + (w + 5) / 2, y + w, r, 0, PI, false);
     ctx.lineTo(x, y + w);
     ctx.arc(x, y + w / 2, r, 0.5 * PI, 1.5 * PI, true);
     ctx.lineTo(x, y);
     //修饰,没有会看不出效果
     ctx.lineWidth = 1;
     ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
     ctx.strokeStyle = "rgba(255, 255, 255, 0.5)";
     ctx.stroke();
     ctx[type]();
     ctx.globalCompositeOperation = "xor";
    }
    

    注释:

    参数是传入canvas对象

    x,y轴数据

    剪切还是填充的canvas函数(fill,clip)

    绘制难点:(很重要,不然你没法理解它怎么绘制的)

    绘制主要是需要理解这里的绘制是根据你设置一个起始点坐标,然后你绘制第二次的时候线就会连接到第二个点,依次连接最后回到原点就形成一个完整的图形。

    Vue实现滑动拼图验证码
    用的是arc参数,主要是看这个图

    fill是用于填充绘制的部分,clip是裁剪出绘制的部分,利用这个就可以出现一个扣掉的图片和一个裁剪出来的图片。

    完成之后就是我的那个函数了。大家可以直接拿去用。

    • 让元素跟随鼠标点击之后滑动

    原理:

    鼠标点击之后记录当前坐标,然后随着(mousemove)滚动的时候修改元素的left和top值就行了。

    还有一点就是鼠标快速滑动会导致丢失滑动效果,这里需要用document,不能是元素级别的监听。

    元素上面只需要鉴定按下mousedown

    代码:

    //鼠标按下
    drag(e) {
     console.log("鼠标按下", e);
     let dom = e.target; //dom元素
     let slider = document.querySelector("#sliderBlock"); //滑块dom
     const downCoordinate = { x: e.x, y: e.y };
     //正确的滑块数据
     let checkx = Number(this.slider.mx) - Number(this.slider.bx);
     //x轴数据
     let x = 0;
     const move = moveEV => {
     x = moveEV.x - downCoordinate.x;
     //y = moveEV.y - downCoordinate.y;
     if (x >= 251 || x <= 0) return false;
     dom.style.left = x + "px";
     //dom.style.top = y + "px";
     slider.style.left = x + "px";
     };
     const up = () => {
     document.removeEventListener("mousemove", move);
     document.removeEventListener("mouseup", up);
     dom.style.left = "";
     console.log(x, checkx);
     let max = checkx - 5;
     let min = checkx - 10;
     //允许正负误差1
     if ((max >= x && x >= min) || x === checkx) {
     console.log("滑动解锁成功");
     this.puzzle = true;
     this.tips = "验证成功";
     setTimeout(() => {
     this.visible = false;
     }, 500);
     } else {
     console.log("拼图位置不正确");
     this.tips = "验证失败,请重试";
     this.puzzle = false;
     this.canvasInit();
     }
     };
     document.addEventListener("mousemove", move);
     document.addEventListener("mouseup", up);
    }
    
    • 完整的页面代码

      <template>
         <div id="login">
         <el-form class="loginFrom" :model="logindata" :rules="rules" ref="ruleForm">
         <el-form-item class="login-item">
         <h1 class="login-title">登录页面</h1>
         </el-form-item>
         <el-form-item prop="userName">
         <el-input
         class="login-inputorbuttom"
         prefix-icon="el-icon-user"
         placeholder="登录名"
         v-model="logindata.userName"
         ></el-input>
         </el-form-item>
         <el-form-item prop="password">
         <el-input
         class="login-inputorbuttom"
         prefix-icon="el-icon-lock"
         placeholder="密码"
         v-model="logindata.password"
         ></el-input>
         </el-form-item>
         <!--<el-form-item prop="verificationCode">
         <el-input
         class="login-inputorbuttom"
         v-model="logindata.verificationCode"
         ></el-input>
         </el-form-item>-->
         <el-form-item class="login-item">
         <el-button
         class="login-inputorbuttom login-bottom"
         type="primary"
         v-popover:popover
         @click="visible = !visible"
         >登 录</el-button
         >
         </el-form-item>
         </el-form>
         <!--验证码弹窗-->
         <el-popover
         popper-class="slidingPictures"
         ref="popover"
         trigger="manual"
         v-model="visible"
         >
         <div class="sliding-pictures">
         <div class="vimg">
         <canvas id="sliderBlock"></canvas>
         <canvas id="codeImg"></canvas>
         </div>
         <div class="slider">
         <div class="track" :class="{ pintuTrue: puzzle }">
         {{ tips }}
         </div>
         <div class="button el-icon-s-grid" @mousedown.prevent="drag"></div>
         </div>
         <div class="operation">
         <span
         title="关闭验证码"
         @click="visible = false"
         class="el-icon-circle-close"
         ></span>
         <span
         title="刷新验证码"
         @click="canvasInit"
         class="el-icon-refresh-left"
         ></span>
         </div>
         </div>
         </el-popover>
         </div>
        </template>
        <script>
        export default {
         name: "login",
         data() {
         return {
         tips: "拖动左边滑块完成上方拼图",
         logindata: {
         userName: "",
         password: "",
         verificationCode: ""
         },
         rules: {},
         visible: false,
         //滑块x轴数据
         slider: {
         mx: 0,
         bx: 0
         },
         //拼图是否正确
         puzzle: false
         };
         },
         watch: {
         visible(e) {
         if (e === true) {
         this.canvasInit();
         this.puzzle = false;
         }
         }
         },
         beforeCreate() {},
         created() {},
         beforeMount() {},
         mounted() {},
         methods: {
         //拼图验证码初始化
         canvasInit() {
         //生成指定区间的随机数
         const random = (min, max) => {
         return Math.floor(Math.random() * (max - min + 1) + min);
         };
         //x: 254, y: 109
         let mx = random(127, 244),
         bx = random(10, 128),
         y = random(10, 99);
         this.slider = { mx, bx };
         this.draw(mx, bx, y);
         },
         //鼠标按下
         drag(e) {
         console.log("鼠标按下", e);
         let dom = e.target; //dom元素
         let slider = document.querySelector("#sliderBlock"); //滑块dom
         const downCoordinate = { x: e.x, y: e.y };
         //正确的滑块数据
         let checkx = Number(this.slider.mx) - Number(this.slider.bx);
         //x轴数据
         let x = 0;
         const move = moveEV => {
         x = moveEV.x - downCoordinate.x;
         //y = moveEV.y - downCoordinate.y;
         if (x >= 251 || x <= 0) return false;
         dom.style.left = x + "px";
         //dom.style.top = y + "px";
         slider.style.left = x + "px";
         };
         const up = () => {
         document.removeEventListener("mousemove", move);
         document.removeEventListener("mouseup", up);
         dom.style.left = "";
         console.log(x, checkx);
         let max = checkx - 5;
         let min = checkx - 10;
         //允许正负误差1
         if ((max >= x && x >= min) || x === checkx) {
         console.log("滑动解锁成功");
         this.puzzle = true;
         this.tips = "验证成功";
         setTimeout(() => {
         this.visible = false;
         }, 500);
         } else {
         console.log("拼图位置不正确");
         this.tips = "验证失败,请重试";
         this.puzzle = false;
         this.canvasInit();
         }
         };
         document.addEventListener("mousemove", move);
         document.addEventListener("mouseup", up);
         },
         draw(mx = 200, bx = 20, y = 50) {
         let mainDom = document.querySelector("#codeImg");
         let bg = mainDom.getContext("2d");
         let width = mainDom.width;
         let height = mainDom.height;
         let blockDom = document.querySelector("#sliderBlock");
         let block = blockDom.getContext("2d");
         //重新赋值,让canvas进行重新绘制
         blockDom.height = height;
         mainDom.height = height;
         let imgsrc = require("../assets/images/back.jpg");
         let img = document.createElement("img");
         img.style.objectFit = "scale-down";
         img.src = imgsrc;
         img.onload = function() {
         bg.drawImage(img, 0, 0, width, height);
         block.drawImage(img, 0, 0, width, height);
         };
         let mainxy = { x: mx, y: y, r: 9 };
         let blockxy = { x: bx, y: y, r: 9 };
         this.drawBlock(bg, mainxy, "fill");
         this.drawBlock(block, blockxy, "clip");
         },
         //绘制拼图
         drawBlock(ctx, xy = { x: 254, y: 109, r: 9 }, type) {
         let x = xy.x,
         y = xy.y,
         r = xy.r,
         w = 40;
         let PI = Math.PI;
         //绘制
         ctx.beginPath();
         //left
         ctx.moveTo(x, y);
         //top
         ctx.arc(x + (w + 5) / 2, y, r, -PI, 0, true);
         ctx.lineTo(x + w + 5, y);
         //right
         ctx.arc(x + w + 5, y + w / 2, r, 1.5 * PI, 0.5 * PI, false);
         ctx.lineTo(x + w + 5, y + w);
         //bottom
         ctx.arc(x + (w + 5) / 2, y + w, r, 0, PI, false);
         ctx.lineTo(x, y + w);
         ctx.arc(x, y + w / 2, r, 0.5 * PI, 1.5 * PI, true);
         ctx.lineTo(x, y);
         //修饰,没有会看不出效果
         ctx.lineWidth = 1;
         ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
         ctx.strokeStyle = "rgba(255, 255, 255, 0.5)";
         ctx.stroke();
         ctx[type]();
         ctx.globalCompositeOperation = "xor";
         }
         }
        };
        </script>
        <style>
        .slidingPictures {
         padding: 0;
         width: 300px;
         border-radius: 2px;
        }
        </style>
        <style scoped lang="scss">
        #login {
         display: flex;
         flex-flow: row;
         justify-content: flex-end;
         align-items: center;
         width: 100%;
         height: 100%;
         background-image: url("../assets/images/back.jpg");
         background-size: 100% 100%;
         .loginFrom {
         width: 300px;
         margin-top: -10vw;
         margin-right: 10vw;
         .login-item {
         display: flex;
         justify-content: center;
         align-items: center;
         }
         .login-title {
         color: #ffffff;
         font-size: 16px;
         margin-bottom: 10px;
         }
         .login-bottom {
         margin-top: 15px;
         }
         .login-bottom:hover {
         background: rgba(28, 136, 188, 0.5);
         }
         .login-bottom:active {
         background: rgba(228, 199, 200, 0.5);
         }
         /deep/.login-inputorbuttom {
         height: 40px;
         width: 300px;
         background: rgba(57, 108, 158, 0.5);
         border-radius: 20px;
         border: #396c9e 1px solid;
         font-size: 14px;
         color: #ffffff;
         .el-input--small,
         .el-input__inner {
         line-height: 43px;
         border: none;
         color: #ffffff;
         font-size: 14px;
         height: 40px;
         border-radius: 20px;
         background: transparent;
         text-align: center;
         }
         .el-input__icon {
         line-height: 40px;
         font-size: 16px;
         }
         }
         }
        }
        /*该样式最终是以弹窗插入*/
        .sliding-pictures {
         width: 100%;
         .vimg {
         width: 100%;
         height: 170px;
         #codeImg,
         #sliderBlock {
         padding: 7px 7px 0 7px;
         width: inherit;
         height: inherit;
         }
         #codeImg {
         //display: none;
         }
         #sliderBlock {
         position: absolute;
         z-index: 4000;
         }
         }
         .slider {
         width: 100%;
         height: 65px;
         border-bottom: #c7c9d0 1px solid;
         display: flex;
         align-items: center;
         justify-content: flex-start;
         .track {
         margin-left: 7px;
         width: 286px;
         height: 38px;
         background: rgba(28, 136, 188, 0.5);
         border-radius: 25px;
         font-size: 14px;
         line-height: 38px;
         padding-right: 15px;
         padding-left: 70px;
         }
         .pintuTrue {
         background: #67c23a;
         color: #ffffff;
         }
         .button {
         position: absolute;
         width: 50px;
         height: 50px;
         line-height: 48px;
         background: #ffffff;
         box-shadow: #b9bdc8 0 0 3px;
         border-radius: 50%;
         left: 7px;
         text-align: center;
         font-size: 28px;
         color: #3e5d8b;
         &:hover {
         color: #2181bd;
         }
         }
         }
         .operation {
         width: 100%;
         height: 40px;
         > span {
         color: #9fa3ac;
         display: inline-block;
         width: 40px;
         font-size: 25px;
         line-height: 40px;
         text-align: center;
         &:hover {
         background: #e2e8f5;
         }
         }
         }
        }
        </style>
      
    展开全文
  • if(that.$route.path==’/login’&&(e.code==‘Enter’||e.code==‘enter’||e.keyCode==‘13’)){//验证登录界面和按 得键是回车键enter that.handleLogin();//登录函数 } } let accounts=this.getCookie(...

    在这里插入图片描述

    < el-form-item prop=“verifycode” style=“line-height:0px;”>

    < el-input v-model=“loginForm.verifycode” placeholder=“请输入验证码” class=“identifyinput” style=“width:150px;”>< /el-input>
    < div class=“identifybox”>
    < div @click=“refreshCode”>
    < s-identify :identifyCode=“identifyCode”>< /s-identify>
    < /div>
    <el-button @click=“refreshCode” type=‘text’ class=“textbtn” style=“color:#fff;padding:0px 0px”>看不清,换一张< /el-button>
    < /div>
    < /el-form-item>

    import SIdentify from ‘@/components/authCode/index.vue’ //验证码需要用到的生成类
    //验证码需要用到的生成类

    < template>
    < div class=“s-canvas”>
    < canvas id=“s-canvas” :width=“contentWidth” :height=“contentHeight”></ canvas>
    </ div>
    </ template>
    < script>
    export default {
    name: ‘SIdentify’,
    props: {
    identifyCode: {
    type: String,
    default: ‘1234’
    },
    fontSizeMin: {
    type: Number,
    default: 16
    },
    fontSizeMax: {
    type: Number,
    default: 40
    },
    backgroundColorMin: {
    type: Number,
    default: 180
    },
    backgroundColorMax: {
    type: Number,
    default: 240
    },
    colorMin: {
    type: Number,
    default: 50
    },
    colorMax: {
    type: Number,
    default: 160
    },
    lineColorMin: {
    type: Number,
    default: 40
    },
    lineColorMax: {
    type: Number,
    default: 180
    },
    dotColorMin: {
    type: Number,
    default: 0
    },
    dotColorMax: {
    type: Number,
    default: 255
    },
    contentWidth: {
    type: Number,
    default: 112
    },
    contentHeight: {
    type: Number,
    default: 38
    }
    },
    methods: {
    // 生成一个随机数
    randomNum(min, max) {
    return Math.floor(Math.random() * (max - min) + min)
    },
    // 生成一个随机的颜色
    randomColor(min, max) {
    var r = this.randomNum(min, max)
    var g = this.randomNum(min, max)
    var b = this.randomNum(min, max)
    return ‘rgb(’ + r + ‘,’ + g + ‘,’ + b + ‘)’
    },
    drawPic() {
    var canvas = document.getElementById(‘s-canvas’)
    var ctx = canvas.getContext(‘2d’)
    ctx.textBaseline = ‘bottom’
    // 绘制背景
    ctx.fillStyle = this.randomColor(
    this.backgroundColorMin,
    this.backgroundColorMax
    )
    ctx.fillRect(0, 0, this.contentWidth, this.contentHeight)
    // 绘制文字
    for (let i = 0; i < this.identifyCode.length; i++) {
    this.drawText(ctx, this.identifyCode[i], i)
    }
    //this.drawLine(ctx)
    //this.drawDot(ctx)
    },
    drawText(ctx, txt, i) {
    ctx.fillStyle = this.randomColor(this.colorMin, this.colorMax)
    ctx.font =
    this.randomNum(this.fontSizeMin, this.fontSizeMax) + ‘px SimHei’
    var x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))
    var y = this.randomNum(this.fontSizeMax, this.contentHeight - 5)
    var deg = this.randomNum(-45, 45)
    // 修改坐标原点和旋转角度
    ctx.translate(x, y)
    ctx.rotate(deg * Math.PI / 180)
    ctx.fillText(txt, 0, 0)
    // 恢复坐标原点和旋转角度
    ctx.rotate(-deg * Math.PI / 180)
    ctx.translate(-x, -y)
    },
    drawLine(ctx) {
    // 绘制干扰线
    for (let i = 0; i < 8; i++) {
    ctx.strokeStyle = this.randomColor(
    this.lineColorMin,
    this.lineColorMax
    )
    ctx.beginPath()
    ctx.moveTo(
    this.randomNum(0, this.contentWidth),
    this.randomNum(0, this.contentHeight)
    )
    ctx.lineTo(
    this.randomNum(0, this.contentWidth),
    this.randomNum(0, this.contentHeight)
    )
    ctx.stroke()
    }
    },
    drawDot(ctx) {
    // 绘制干扰点
    for (let i = 0; i < 100; i++) {
    ctx.fillStyle = this.randomColor(0, 255)
    ctx.beginPath()
    ctx.arc(
    this.randomNum(0, this.contentWidth),
    this.randomNum(0, this.contentHeight),
    1,
    0,
    2 * Math.PI
    )
    ctx.fill()
    }
    }
    },
    watch: {
    identifyCode() {
    this.drawPic()
    }
    },
    mounted() {
    this.drawPic()
    }
    }
    < /script>

    //验证码需要用到的生成类

    export default {
    name: ‘Login’,
    components: {
    SIdentify
    },
    data() {
    const validateUsername = (rule, value, callback) => {
    if (!value) {
    callback(new Error(‘请输入用户名’))
    } else {
    callback()
    }
    }
    const validatePassword = (rule, value, callback) => {
    if (!value) {
    callback(new Error(‘请输入密码’))
    } else {
    if(value.length < 6){
    callback(new Error(‘请输入至少6位密码’))
    }else{
    callback()
    }
    }
    }
    // 验证码自定义验证规则
    const validateVerifycode = (rule, value, callback) => {
    if (value === ‘’) {
    callback(new Error(‘请输入验证码’))
    } else if (value !== this.identifyCode) {
    console.log(‘validateVerifycode:’, value)
    callback(new Error(‘验证码不正确!’))
    } else {
    callback()
    }
    }
    return {
    identifyCodes: ‘1234567890’,
    identifyCode: ‘’,
    loginForm: {
    username: this.username,
    password: this.password,
    verifycode: ‘’
    },
    checked: false,
    loginRules: {
    username: [{ required: true, trigger: ‘blur,change’, validator: validateUsername }],
    password: [{ required: true, trigger: ‘blur,change’, validator: validatePassword }],
    verifycode: [
    { required: true, trigger: ‘blur’, validator: validateVerifycode }
    ]
    },
    }
    },
    mounted() {
    // 验证码初始化
    this.identifyCode = ‘’
    this.makeCode(this.identifyCodes, 4)
    },
    created(){
    let that = this;
    document.onkeydown =function(e){
    e = window.event || e;
    //支持小键盘和大键盘
    if(that.$route.path==’/login’&&(e.code==‘Enter’||e.code==‘enter’||e.keyCode==‘13’)){//验证在登录界面和按 得键是回车键enter
    that.handleLogin();//登录函数
    }
    }
    let accounts=this.getCookie(“account”)
    if(accounts){
    this.loginForm.username=accounts
    }
    },
    methods: {
    // 生成随机数
    randomNum(min, max) {
    return Math.floor(Math.random() * (max - min) + min)
    },
    // 切换验证码
    refreshCode() {
    this.identifyCode = ‘’
    this.makeCode(this.identifyCodes, 4)
    },
    // 生成四位随机验证码
    makeCode(o, l) {
    for (let i = 0; i < l; i++) {
    this.identifyCode += this.identifyCodes[
    this.randomNum(0, this.identifyCodes.length)
    ]
    }
    },
    handleLogin() {
    this. KaTeX parse error: Expected '}', got 'EOF' at end of input: … this.store.dispatch(‘user/login’, this.loginForm).then(() => {
    this.$router.push({ path: this.redirect || ‘/’ })
    this.loading = false
    }).catch(() => {
    this.refreshCode()
    this.loading = false
    })
    } else {
    this.refreshCode()
    //console.log(‘error submit!!’)
    return false
    }
    })
    },
    // 保存cookie
    setCookie: function (cName, value, expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = cName + ‘=’ + decodeURIComponent(value) +
    ((expiredays == null) ? ‘’ : ‘;expires=’ + exdate.toGMTString())
    },
    // 获取cookie
    getCookie: function (key) {
    if (document.cookie.length > 0) {
    var start = document.cookie.indexOf(key + ‘=’)
    if (start !== -1) {
    start = start + key.length + 1
    var end = document.cookie.indexOf(’;’, start)
    if (end === -1) end = document.cookie.length
    return unescape(document.cookie.substring(start, end))
    }
    }
    return ‘’
    },
    }

    展开全文
  • vue登录验证进行路由拦截

    千次阅读 2018-06-28 14:23:06
    表单验证部分使用elementUI里面提供的简单验证办法&lt;el-form :model="ruleForm2" :rules="rules2" ref="ruleForm2" label-position="left" label-width="0px&...
  • 滑动验证(login.vue 和 hd.vue 相关) login.vue <template> <body id="poster"> <el-form class="login-container" label-position="left" label-width="0px" :rules="loginFormRules" :model=...
  • ensure_ascii=False),content_type="application/json,charset=utf-8") return respon class Test2(MiddlewareMixin): def process_request(self, request): print("这是一个中间件 --> test2") view.py #登录验证 ...
  • vue验证登录

    万次阅读 2017-11-06 11:03:56
    vue验证登录
  • 主要为大家详细介绍了vue登录路由验证的实现,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • 主要介绍了vue 登录滑动验证实现代码,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
  • vue登录滑动验证

    2020-12-03 23:34:44
    1、引入vue-monoplasty-slide-verify组件到项目里 先使用命令行安装:npm install --save vue-monoplasty-slide-verify 2、在main.js目录下添加代码 import Vue from 'vue'; import SlideVerify from 'vue-...
  • vue登录验证

    2021-01-28 21:29:31
    vue登录验证 sessionStorage和router.beforeEach结合使用 1.点击登录按钮后设置sessionStorage的值,如 <!--从后端返回这个登录的对象,如果不为null,设置sessionStorage的值为100--> axios.post('...
  • vue滑块验证登录

    2020-11-05 20:47:00
    this.form.checkMove) { this.$message({ message: '滑块验证有误,请重新验证', type: 'warning' }); return; } let params = { // ... } //发送短信验证码接口 sendVerificationCode({ data: params }).then(res =...
  • vue 登录注册验证

    千次阅读 2019-06-05 17:14:34
    <template> <div class="page"> <div class="login-box"> <p data-v-032893be class="title">欢迎登录</p> <el-tabs v-model="activeName"> <el-tab...
  • vue 登录滑动验证

    千次阅读 2018-04-23 18:26:55
    之前别人都是用jq写的,自己整理了一下开始使用&...验证"&gt; &lt;div class="form-inline-input"&gt; &lt;div class="code-box" id="code-box"&gt;
  • vue登录验证

    千次阅读 2018-05-18 16:00:52
    在项目开发中,我们通常会需要在进入主页时(或其他需要...这时,我们需要配置路由的验证方法const routes={ routes: [ { path: '/login', name:'登录', component: login },{ path: '/', name:'home', ...
  • springboot-整合shiro和vue验证登录和权限

    万次阅读 热门讨论 2018-11-20 01:03:52
    配置1.1数据表这里权限控制有5张表,详情见代码中的test.sql文件1.2工程说明:1.3springboot下的shiro配置1.4shiro登录验证的使用:1.5前端采用vue2.测试 完整代码下载链接: https://github.com/2010yhh...
  • 主要介绍了vue登录以及权限验证相关的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,666
精华内容 666
关键字:

vue登录验证

vue 订阅