欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue實現(xiàn)驗證碼登錄全過程

 更新時間:2025年03月20日 09:38:12   作者:沙漠真有魚  
這篇文章主要介紹了Vue實現(xiàn)驗證碼登錄全過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

在我們進行登錄的時候,為了保護系統(tǒng)的安全性,也是防止惡意進行登錄,進入到后臺盜取數(shù)據(jù),因此我們在登錄的環(huán)節(jié)進行一定的安全保護,提升系統(tǒng)安全等級。

在此我們運用阿拉伯數(shù)字和英文字母進行4位數(shù)的驗證碼校驗,當然也可以進行多位字符進行校驗,在此我使用生成4位驗證碼進行校驗

驗證碼:前端綁定后端生成得驗證碼圖片,前端提交表單信息到后端進行驗證,后端驗證碼存入session

一、環(huán)境準備

我這里由于本機上的還是vue 2 所以這邊還是vue2開發(fā)的,而且主要是好嫖組件,畢竟不是專業(yè)的前端。

這里的話由于某些原因,我這里使用的包管理是 cnpm

不為別的就為了安裝的時候不會被雷到。

這里先裝一個 vuex 用來管理狀態(tài),怎么裝一條命令的事情。

二、功能展示

三、項目結(jié)構(gòu)

四、驗證碼生成

<template>
  <div class="ValidCode disabled-select"
       :style="`width:${width}; height:${height}`"
       @click="refreshCode">
    <span v-for="(item, index) in codeList"
          :key="index"
          :style="getStyle(item)">
      {{item.code}}
    </span>
  </div>
</template>
<script>
export default {
  name: "ValidCode",
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    width: {
      type: String,
      default: '100px'
    },
    height: {
      type: String,
      default: '34px'
    },
    length: {
      type: Number,
      default: 4
    }
  },
  data () {
    return {
      codeList: []
    }
  },
  mounted () {
    this.createdCode()
  },
  methods: {
    refreshCode () {
      this.createdCode()
    },
    createdCode () {
      const len = this.length
      const codeList = []
      const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789'
      const charsLen = chars.length
      // 生成
      for (let i = 0; i < len; i++) {
        const rgb = [Math.round(Math.random() * 220), Math.round(Math.random() * 240), Math.round(Math.random() * 200)]
        codeList.push({
          code: chars.charAt(Math.floor(Math.random() * charsLen)),
          color: `rgb(${rgb})`,
          fontSize: `1${[Math.floor(Math.random() * 10)]}px`,
          padding: `${[Math.floor(Math.random() * 10)]}px`,
          transform: `rotate(${Math.floor(Math.random() * 90) - Math.floor(Math.random() * 90)}deg)`
        })
      }
      // 指向
      this.codeList = codeList
      // 將當前數(shù)據(jù)派發(fā)出去
      this.$emit('input', codeList.map(item => item.code).join(''))
    },
    getStyle (data) {
      return `color: ${data.color}; font-size: ${data.fontSize}; padding: ${data.padding}; transform: ${data.transform}`
    }
  }
}
</script>
<style scoped >
.ValidCode{
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  span{
    display: inline-block;
  }
}
</style>

五、驗證碼使用

1.首先需要解決的是登錄的跨域問題,使用我們的axios進行解決:

import axios from 'axios'
import {serverIp} from "../../public/config";

const request = axios.create({
    baseURL: `http://localhost:9090`,  // 注意??! 這里是全局統(tǒng)一加上了 '/api' 前綴,也就是說所有接口都會加上'/api'前綴在,頁面里面寫接口的時候就不要加 '/api'了,否則會出現(xiàn)2個'/api',類似 '/api/api/user'這樣的報錯,切記?。?!
    timeout: 5000
})

// request 攔截器
// 可以自請求發(fā)送前對請求做一些處理
// 比如統(tǒng)一加token,對請求參數(shù)統(tǒng)一加密
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
    if (user) {
        config.headers['token'] = user.token;  // 設置請求頭
    }

    return config
}, error => {
    return Promise.reject(error)
});

// response 攔截器
// 可以在接口響應后統(tǒng)一處理結(jié)果
request.interceptors.response.use(
    response => {
        let res = response.data;
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
            return res
        }
        // 兼容服務端返回的字符串數(shù)據(jù)
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        return res;
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)


export default request

2.在需要的頁面進行引入

<script>
import request from "@/utils/request";
import ValidCode from "@/components/ValidCode";
const Base64 = require('js-base64').Base64

export default {
  name: "Login",
  components: {
    ValidCode
  },
  data() {
    return {
      form: {
        sex: 1,
        username: '',
        password: '',
      },
      checked: false,
      rules: {
        username: [
          {required: true, message: '請輸入用戶名', trigger: 'blur'},
          {min: 3, max: 10, message: "長度在3到10個字符", trigger: "blur"},
        ],
        password: [
          {required: true, message: '請輸入密碼', trigger: 'blur'},
          {min: 1, max: 20, message: '長度在 6 到 11 個字符', trigger: 'blur'}
        ],
      },
      validCode: '',
    }
  },
}
</script>

3.驗證碼校驗

<ek-form-item>
    <div style="display: flex">
        <el-input v-model="form.validCode" style="width: 60%" placeholder="請輸入驗證碼" size="medium"></el-input>
        <ValidCode @input="createValidCode" />
    </div>
</ek-form-item>
export default {
  name: "Login",
  components: {
    ValidCode
  },
  data() {
    return {
      form: {
        sex: 1,
        username: '',
        password: '',
      },
      checked: false,
      rules: {
        username: [
          {required: true, message: '請輸入用戶名', trigger: 'blur'},
          {min: 3, max: 10, message: "長度在3到10個字符", trigger: "blur"},
        ],
        password: [
          {required: true, message: '請輸入密碼', trigger: 'blur'},
          {min: 1, max: 20, message: '長度在 6 到 11 個字符', trigger: 'blur'}
        ],
      },
      validCode: '',
    }
  },
}

4.完整代碼

<template>
  <div style="height: 100vh; overflow: hidden">
    <div style="height: 50px;
      line-height: 50px;
      border-bottom: 2px solid var(--colorRed);
      padding-left: 20px;
      color: var(--colorRed)">
      <b style="font-size: 24px;">xx宿舍</b>
      <i style="margin-left: 20px">-- 只為更好的你</i>
    </div>
    <div style="width: 50%;
      margin: 50px auto;
      border-radius: 10px;
      box-shadow: 0 0 10px -2px cornflowerblue;
      display: flex">
      <div style="flex: 1; padding: 50px 50px">
        <img src="../assets/images/學習.png" alt="" style="width: 100%;">
      </div>
      <div style="flex: 1; padding: 20px">
        <div class="form-toggle">
          <b >賬號登錄</b>
        </div>
        <el-form ref="form" :model="form" size="normal" :rules="rules" >
          <el-form-item prop="username" class="props">
            <el-input  placeholder="賬號" clearable v-model="form.username" prefix-icon="el-icon-user" />
          </el-form-item>
          <el-form-item prop="password" class="props">
            <el-input placeholder="密碼" v-model="form.password" show-password prefix-icon="el-icon-lock" />
          </el-form-item>
          <ek-form-item>
            <div style="display: flex">
              <el-input v-model="form.validCode" style="width: 60%" placeholder="請輸入驗證碼" size="medium"></el-input>
              <ValidCode @input="createValidCode" />
            </div>
          </ek-form-item>
          <el-form-item style="padding-top:15px">
            <el-button type="primary" style="width: 100%" @click="login" round>登 錄</el-button>
          </el-form-item>
<!--          <el-form-item>-->
            <div style="margin: 10px 0; text-align: right;">
              <a href="/register" rel="external nofollow"  style="color: var(--colorRed)">立即注冊</a>
            </div>
<!--            <el-button  style="width: 100%" @click="register" round>點擊注冊</el-button>-->
<!--          </el-form-item>-->
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";
import ValidCode from "@/components/ValidCode";
const Base64 = require('js-base64').Base64

export default {
  name: "Login",
  components: {
    ValidCode
  },
  data() {
    return {
      form: {
        sex: 1,
        username: '',
        password: '',
      },
      checked: false,
      rules: {
        username: [
          {required: true, message: '請輸入用戶名', trigger: 'blur'},
          {min: 3, max: 10, message: "長度在3到10個字符", trigger: "blur"},
        ],
        password: [
          {required: true, message: '請輸入密碼', trigger: 'blur'},
          {min: 1, max: 20, message: '長度在 6 到 11 個字符', trigger: 'blur'}
        ],
      },
      validCode: '',
    }
  },
  mounted () {
    let username = localStorage.getItem('username')
    if (username) {
      this.form.username = localStorage.getItem('username')
      this.form.password = Base64.decode(localStorage.getItem('password'))// base64解密
      this.checked = true
    }
  },
  created() {
    sessionStorage.removeItem("user")
  },
  methods: {
    register:function(){
      this.$router.push("/register");
    },
    //接收驗證碼組件提交的4位驗證碼
    createValidCode(data) {
      this.validCode = data
    },
    login() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (!this.form.validCode) {
            this.$message.error("請?zhí)顚戲炞C碼")
            return
          }
          if (this.form.validCode.toLowerCase() !== this.validCode.toLowerCase()) {
            this.$message.error("驗證碼錯誤")
            return
          }
          request.post("/user/login", this.form).then(res => {
            if (res.code === '200'){
              // sessionStorage.setItem("user", JSON.stringify(res.data))//緩存用戶信息
              localStorage.setItem("user", JSON.stringify(res.data))
              if (res.data.role === 'USER') {
                this.$router.push("/")
              } else {
                this.$router.push("/mall/index")
              }
              this.$message({
                type: "success",
                message: "登錄成功"
              })
            } else {
              this.$message({
                type: "error",
                message: res.msg
              })
            }
          })
        }
      });
    },
  }
}
</script>

<style scoped>
.form-toggle {
  margin: 20px 0;
  text-align: center
}
.form-toggle b {
  font-size: 20px;
  cursor: pointer;
}
</style>

附送

全局定義css并在main.js里面引入

import './assets/css/global.css'

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.ml-5 {
    margin-left: 5px;
}
.ml-10 {
    margin-left: 10px;
}
.mr-5 {
    margin-right: 5px;
}
.pd-10 {
    padding: 10px;
}
body {
    margin: 0;
    padding: 0;
    font-size: 14px;
    color: #666;
    --colorRed: orangered;
}
a {
    text-decoration: none;
}

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • vue項目登錄模塊滑塊拼圖驗證功能實現(xiàn)代碼(純前端)

    vue項目登錄模塊滑塊拼圖驗證功能實現(xiàn)代碼(純前端)

    滑塊驗證作為一種反機器人的工具,也會不斷發(fā)展和演進,以適應不斷變化的威脅,這篇文章主要給大家介紹了vue項目登錄模塊滑塊拼圖驗證功能實現(xiàn)的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-07-07
  • Vue.js快速入門實例教程

    Vue.js快速入門實例教程

    vue是法語中視圖的意思,Vue.js是一個輕巧、高性能、可組件化的MVVM庫,同時擁有非常容易上手的API。這篇文章主要介紹了Vue.js快速入門實例教程的相關資料,需要的朋友可以參考下
    2016-10-10
  • 怎樣查看vue-cli的安裝位置

    怎樣查看vue-cli的安裝位置

    這篇文章主要介紹了怎樣查看vue-cli的安裝位置問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • vue使用axios訪問本地json文件404問題及解決

    vue使用axios訪問本地json文件404問題及解決

    這篇文章主要介紹了vue使用axios訪問本地json文件404問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • VueJS頁面渲染之后如何調(diào)用函數(shù)

    VueJS頁面渲染之后如何調(diào)用函數(shù)

    這篇文章主要介紹了VueJS頁面渲染之后如何調(diào)用函數(shù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • vue使用Pinia的五個實用技巧分享

    vue使用Pinia的五個實用技巧分享

    這篇文章主要為大家詳細介紹了vue中使用Pinia是五個實用技巧,文中的示例代碼講解詳細,具有一定的學習價值,感興趣的小伙伴可以跟隨小編一起了解一下
    2023-11-11
  • vue.js使用watch監(jiān)聽路由變化的方法

    vue.js使用watch監(jiān)聽路由變化的方法

    這篇文章主要介紹了vue.js使用watch監(jiān)聽路由變化的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-07-07
  • Vue下拉框值變動事件傳多個參數(shù)方式

    Vue下拉框值變動事件傳多個參數(shù)方式

    這篇文章主要介紹了Vue下拉框值變動事件傳多個參數(shù)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • 詳解使用element-ui table組件的篩選功能的一個小坑

    詳解使用element-ui table組件的篩選功能的一個小坑

    在element ui 框架中,對于table框架,有一個篩選功能,這篇文章主要介紹了詳解使用element-ui table組件的篩選功能的一個小坑,非常具有實用價值,需要的朋友可以參考下
    2018-11-11
  • element-UI el-table修改input值視圖不更新問題

    element-UI el-table修改input值視圖不更新問題

    這篇文章主要介紹了element-UI el-table修改input值視圖不更新問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02

最新評論