当前位置:首页 > VUE

vue实现验证码

2026-01-11 20:21:46VUE

Vue 实现验证码的方法

使用 Canvas 生成图形验证码

安装依赖(如需要):

npm install vue-canvas-verify --save

创建验证码组件:

<template>
  <div class="captcha">
    <canvas ref="canvas" width="120" height="40" @click="refresh"></canvas>
    <input v-model="inputCode" placeholder="请输入验证码"/>
  </div>
</template>

<script>
export default {
  data() {
    return {
      code: '',
      inputCode: ''
    }
  },
  mounted() {
    this.drawCode()
  },
  methods: {
    drawCode() {
      const ctx = this.$refs.canvas.getContext('2d')
      ctx.clearRect(0, 0, 120, 40)

      // 生成随机验证码
      this.code = Math.random().toString(36).substr(2, 4).toUpperCase()

      // 绘制背景
      ctx.fillStyle = '#f5f5f5'
      ctx.fillRect(0, 0, 120, 40)

      // 绘制文字
      ctx.font = '24px Arial'
      ctx.fillStyle = '#333'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'
      ctx.fillText(this.code, 60, 20)

      // 绘制干扰线
      for(let i=0; i<5; i++) {
        ctx.strokeStyle = this.randomColor()
        ctx.beginPath()
        ctx.moveTo(Math.random()*120, Math.random()*40)
        ctx.lineTo(Math.random()*120, Math.random()*40)
        ctx.stroke()
      }
    },
    randomColor() {
      return `rgb(${Math.floor(Math.random()*256)}, ${Math.floor(Math.random()*256)}, ${Math.floor(Math.random()*256)})`
    },
    refresh() {
      this.drawCode()
      this.inputCode = ''
    },
    validate() {
      return this.inputCode.toUpperCase() === this.code
    }
  }
}
</script>

使用第三方库 vue-verify-code

安装:

npm install vue-verify-code

使用示例:

<template>
  <verify-code 
    :width="120"
    :height="40"
    @success="handleSuccess"
    @error="handleError"
    ref="verifyCode"
  />
</template>

<script>
import VerifyCode from 'vue-verify-code'

export default {
  components: { VerifyCode },
  methods: {
    handleSuccess(code) {
      console.log('验证成功:', code)
    },
    handleError() {
      console.log('验证失败')
    },
    refresh() {
      this.$refs.verifyCode.refresh()
    }
  }
}
</script>

短信/邮箱验证码实现

发送验证码按钮组件:

<template>
  <button 
    :disabled="countdown > 0"
    @click="sendCode"
  >
    {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
  </button>
</template>

<script>
export default {
  data() {
    return {
      countdown: 0
    }
  },
  methods: {
    sendCode() {
      if (this.countdown > 0) return

      // 调用API发送验证码
      this.$api.sendVerifyCode().then(() => {
        this.countdown = 60
        const timer = setInterval(() => {
          this.countdown--
          if (this.countdown <= 0) {
            clearInterval(timer)
          }
        }, 1000)
      })
    }
  }
}
</script>

验证码校验逻辑

在表单提交时验证:

vue实现验证码

methods: {
  submitForm() {
    if (!this.validateCode()) {
      alert('验证码错误')
      return
    }
    // 提交表单逻辑
  },
  validateCode() {
    // 图形验证码验证
    // return this.$refs.captcha.validate()

    // 或短信验证码验证
    return this.inputCode === this.receivedCode
  }
}

安全注意事项

验证码有效期应设置合理时间(通常5分钟) 验证码应区分大小写或统一转换为大写/小写比较 后端必须进行二次验证,前端验证仅用于用户体验 限制单位时间内验证码发送次数,防止短信轰炸 验证码应包含数字和字母组合,避免使用简单模式

标签: 验证码vue
分享给朋友:

相关文章

vue 实现目录

vue 实现目录

Vue 实现目录的方法 在 Vue 项目中实现目录功能,可以通过以下几种方式实现,具体取决于需求和技术栈。 使用 Vue Router 实现路由目录 Vue Router 是 Vue.js 的官方路…

vue实现简单的弹窗

vue实现简单的弹窗

使用 Vue 实现简单弹窗 组件基础结构 创建一个名为 Modal.vue 的组件文件,包含模板、脚本和样式部分: <template> <div class="mod…

vue实现选择本地文件

vue实现选择本地文件

实现文件选择功能 在Vue中实现本地文件选择可以通过HTML原生的<input type="file">元素实现。创建一个基本的文件选择组件: <template> &l…

vue手写签名如何实现

vue手写签名如何实现

实现手写签名的基本思路 在Vue中实现手写签名功能,通常需要借助HTML5的Canvas API来捕获用户的绘制操作。核心流程包括初始化画布、监听触摸/鼠标事件、记录轨迹以及生成签名图片。 安装依赖…

vue实现xterm

vue实现xterm

在 Vue 中集成 Xterm.js Xterm.js 是一个基于 TypeScript 的前端终端组件库,可用于在浏览器中实现终端功能。以下是在 Vue 项目中集成 Xterm.js 的详细步骤。…

vue实现录音

vue实现录音

Vue 实现录音功能 在 Vue 中实现录音功能可以通过浏览器提供的 MediaRecorder API 完成。以下是具体实现方法: 引入依赖 确保项目支持现代浏览器 API,无需额外安装库。若需兼…