用戶登錄🔒~生成圖片驗證碼(identify(生成圖片驗證碼)插件)

1.效果圖:

2.以用戶登錄實現 生成圖片驗證功能:使用 identify(生成圖片驗證碼)插件

identify:這是一個vue的插件,使用canvas來生成圖形驗證碼

2.1 下載identify插件,npm安裝 
npm i identify
2.2 具體參數如下:

2.2 在components目錄新建一個SIdentify.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: 20
        },
        fontSizeMax: {
          type: Number,
          default: 35
        },
        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) {
          let r = this.randomNum(min, max)
          let g = this.randomNum(min, max)
          let b = this.randomNum(min, max)
          return 'rgb(' + r + ',' + g + ',' + b + ')'
        },
        drawPic () {
          let canvas = document.getElementById('s-canvas')
          let 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'
          let x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))
          let 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 < 3; 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 < 30; 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>
2.3 在你需要驗證碼的頁面引入組件並寫好方法

也可以main.js 中註冊全局註冊

import SIdentify from './components/page/identify'
Vue.use(SIdentify)

也可以組件中直接引入註冊使用

登錄表單loginForm
       <!-- 登錄的表單區域 -->
      <el-form :model="loginForm" :rules="loginRules" ref="loginForm">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="請輸入用戶名" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" placeholder="請輸入密碼" prefix-icon="el-icon-lock"></el-input>
        </el-form-item>

        <el-form-item label="" prop="code">
          <el-input v-model="loginForm.code" style='width:54%;display:inline-block;vertical-align:top;'
            prefix-icon="el-icon-check" placeholder="請輸入驗證碼" @keyup.enter.native="submit('loginForm')">
          </el-input>
          <s-identify style='display:inline-block;margin-left: 40px; height:40px;vertical-align:top;cursor:pointer;'
            :identifyCode="code" :contentHeight='40' @click.native="handleRefreshCode" />
        </el-form-item>

        <el-form-item prop="password">
          <el-button type="primary" class="login-btn" @click="login">登錄</el-button>
          <el-link type="info" @click="$router.push('/reg')">去註冊</el-link>
        </el-form-item>
      </el-form>

data return裏的數據

2.4 自定義校驗規則:自定義提示

rules自定義提示~
     //驗證碼
        code: [
          { required: true, message: '請輸入驗證碼', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.code) {
                callback(new Error('驗證碼錯誤!重新輸入~'));
              }else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
2.5 隨機生成驗證碼
    handleRefreshCode() {
      this.code = (Math.random() * 8999 + 1000).toFixed(0).toString();
    },
methods
   methods: {
    handleRefreshCode() {
      this.code = (Math.random() * 8999 + 1000).toFixed(0).toString();
    },
    // 輸入框確定按鈕事件
    submit(name) {
      // 後端交互時需註釋
      // 沒有登陸接口時,直接放開登陸,默認以超級管理員登陸
      // var userInfo = {
      //   nickname: "超級管理員",
      //   username: 'admin',
      //   roles: 1,
      //   token: "eyJhbGciOiJIUzI1NiJ9.eyJqd3Qt",
      //   "isAuth": false // true開啓權限驗證模式 ,false 不使用權限驗證,默認無權限驗證
      // };
      if (!this.loginForm.code) {
        console.log(this.loginForm.code)

        this.$message.error('請輸入驗證碼!');
        // this.loading = false;
        // this.$progress.done();
      } else if (this.loginForm.code !== this.code) {
        this.$message.error('驗證碼錯誤!')
      } else {
        console.log(this.loginForm.code);
        return this.loginForm.code
      }
      // this.$ls.set('userInfo',userInfo);
      // this.success('登陸成功!');
      // this.$router.push('/');
      return;
      // ============



      // ---
    },
    login() {
      this.$refs.loginForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/api/login', this.loginForm)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // console.log(res.token)
        //利用localstorage存儲到本地
        // localStorage.setItem("token",res.token)

        //利用localstorage獲取本地已存儲的token
        // localStorage.getItem('token')

        //利用localstorage刪除本地已存儲的token
        // localStorage.removeItem('token')

        // ***將 token 存儲至 vuex
        this.$store.commit('user/updateToken', res.token)


        this.$router.push('/')
      })

    },
    // ---


  }

3. 完整代碼

完整code
 <template>
  <!-- 登錄頁面的整體盒子 -->
  <div class="login-container">
    <!-- 登錄的盒子 -->
    <div class="login-box">
      <!-- 標題的盒子 -->
      <div class="title-box"></div>
      <!-- 登錄的表單區域 -->
      <el-form :model="loginForm" :rules="loginRules" ref="loginForm">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="請輸入用戶名" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" placeholder="請輸入密碼" prefix-icon="el-icon-lock"></el-input>
        </el-form-item>

        <el-form-item label="" prop="code">
          <el-input v-model="loginForm.code" style='width:54%;display:inline-block;vertical-align:top;'
            prefix-icon="el-icon-check" placeholder="請輸入驗證碼" @keyup.enter.native="submit('loginForm')">
          </el-input>
          <s-identify style='display:inline-block;margin-left: 40px; height:40px;vertical-align:top;cursor:pointer;'
            :identifyCode="code" :contentHeight='40' @click.native="handleRefreshCode" />
        </el-form-item>

        <el-form-item prop="password">
          <el-button type="primary" class="login-btn" @click="login">登錄</el-button>
          <el-link type="info" @click="$router.push('/reg')">去註冊</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import SIdentify from '@/views/SIdentify/SIdentify.vue'
export default {
  components: { SIdentify },
  name: 'Login',
  data() {
    return {
      loading: false,
      code: '6666',
      loginForm: {
        username: '',
        password: '',
        code: '',
        type: 1
      },
      loginRules: {
        username: [
          { required: true, message: '請輸入用戶名稱', trigger: 'blur', },
          // {min:2,max:5,message: '用戶名稱長度是2-5字符之間',trigger: 'blur'}
          // pattern: 指定正則來匹配
          { pattern: /^[a-zA-Z][a-zA-Z0-9]{0,9}$/, message: '用戶名必須是1 ~ 10位的字母或數字, 不能以數字開頭', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '請輸入密碼', trigger: 'blur', },
          // {min:6,max:15,message: '密碼長度是6-15字符之間',trigger: 'blur'}
          // pattern: 指定正則來匹配
          { pattern: /^\S{6,15}$/, message: '密碼必須是6 ~ 15位的非空字符', trigger: 'blur' }
        ],
        //驗證碼
        code: [
          { required: true, message: '請輸入驗證碼', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.code) {
                callback(new Error('驗證碼錯誤!重新輸入~'));
              }else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      },

    }
  },


  methods: {
    handleRefreshCode() {
      this.code = (Math.random() * 8999 + 1000).toFixed(0).toString();
    },
    // 輸入框確定按鈕事件
    submit(name) {
      // 後端交互時需註釋
      // 沒有登陸接口時,直接放開登陸,默認以超級管理員登陸
      // var userInfo = {
      //   nickname: "超級管理員",
      //   username: 'admin',
      //   roles: 1,
      //   token: "eyJhbGciOiJIUzI1NiJ9.eyJqd3Qt",
      //   "isAuth": false // true開啓權限驗證模式 ,false 不使用權限驗證,默認無權限驗證
      // };
      if (!this.loginForm.code) {
        console.log(this.loginForm.code)

        this.$message.error('請輸入驗證碼!');
        // this.loading = false;
        // this.$progress.done();
      } else if (this.loginForm.code !== this.code) {
        this.$message.error('驗證碼錯誤!')
      } else {
        console.log(this.loginForm.code);
        return this.loginForm.code
      }
      // this.$ls.set('userInfo',userInfo);
      // this.success('登陸成功!');
      // this.$router.push('/');
      return;
      // ============



      // ---
    },
    login() {
      this.$refs.loginForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/api/login', this.loginForm)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // console.log(res.token)
        //利用localstorage存儲到本地
        // localStorage.setItem("token",res.token)

        //利用localstorage獲取本地已存儲的token
        // localStorage.getItem('token')

        //利用localstorage刪除本地已存儲的token
        // localStorage.removeItem('token')

        // ***將 token 存儲至 vuex
        this.$store.commit('user/updateToken', res.token)


        this.$router.push('/')
      })

    },
    // ---


  }

}
</script>

<style lang="less" scoped>
.login-container {
  background: url('../../assets/images/login_bg.jpg') center;
  background-size: cover;
  height: 100%;

  .login-box {
    width: 400px;
    height: 370px;
    background-color: #fff;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding: 0 30px;
    box-sizing: border-box;
    box-shadow: 8px 8px 14px rgba(23, 23, 23, 0.5);

    .title-box {
      height: 60px;
      background: url('../../assets/images/login_title.png') center no-repeat;
    }

    .btn-login {
      width: 100%;
    }

    .login-btn {
      width: 100%;
    }

  }
}
</style>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章