当前位置:首页 > VUE

验证码实现vue

2026-02-25 14:43:27VUE

验证码实现(Vue.js)

使用纯前端生成图形验证码

安装 vaptchavue-captcha 等专用库:

npm install vue-captcha --save

组件引入示例:

验证码实现vue

<template>
  <vue-captcha 
    :length="4" 
    @change="onCaptchaChange"
  />
</template>

<script>
import VueCaptcha from 'vue-captcha'
export default {
  components: { VueCaptcha },
  methods: {
    onCaptchaChange(code) {
      console.log('验证码:', code)
    }
  }
}
</script>

结合Canvas绘制验证码

创建独立组件Captcha.vue

<template>
  <canvas 
    ref="canvas" 
    @click="refreshCode"
    width="120" 
    height="40"
  />
</template>

<script>
export default {
  data() {
    return {
      code: ''
    }
  },
  mounted() {
    this.drawCode()
  },
  methods: {
    generateCode() {
      const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      this.code = Array.from({length:4}, 
        () => chars[Math.floor(Math.random()*chars.length)]
      ).join('')
    },
    drawCode() {
      const ctx = this.$refs.canvas.getContext('2d')
      ctx.fillStyle = this.randomColor(180, 240)
      ctx.fillRect(0, 0, 120, 40)

      // 绘制干扰线
      for(let i=0; i<5; i++) {
        ctx.strokeStyle = this.randomColor(40, 180)
        ctx.beginPath()
        ctx.moveTo(
          Math.random()*120, 
          Math.random()*40
        )
        ctx.lineTo(
          Math.random()*120,
          Math.random()*40
        )
        ctx.stroke()
      }

      // 绘制验证码文本
      this.generateCode()
      ctx.font = '26px Arial'
      ctx.textAlign = 'center'
      for(let i=0; i<this.code.length; i++) {
        ctx.fillStyle = this.randomColor(0, 100)
        ctx.fillText(
          this.code[i], 
          30*(i+0.6), 
          28
        )
      }
    },
    randomColor(min, max) {
      const r = min + Math.floor(Math.random()*(max-min))
      const g = min + Math.floor(Math.random()*(max-min))
      const b = min + Math.floor(Math.random()*(max-min))
      return `rgb(${r},${g},${b})`
    },
    refreshCode() {
      this.drawCode()
      this.$emit('update:code', this.code)
    }
  }
}
</script>

服务端验证方案

前端调用示例:

验证码实现vue

async submitForm() {
  const isValid = await this.$refs.captcha.validate(inputCode)
  if(!isValid) {
    alert('验证码错误')
    return
  }
  // 继续提交表单
}

后端Node.js验证逻辑示例:

app.post('/verify', (req, res) => {
  const { inputCode, sessionCode } = req.body
  if(inputCode.toLowerCase() === sessionCode.toLowerCase()) {
    res.json({ valid: true })
  } else {
    res.json({ valid: false })
  }
})

滑动验证码集成

使用第三方服务如极验:

<template>
  <div id="geetest-captcha"></div>
</template>

<script>
export default {
  mounted() {
    initGeetest({
      gt: "YOUR_GT_KEY",
      challenge: "SERVER_GENERATED_CHALLENGE",
      offline: false
    }, (captchaObj) => {
      captchaObj.appendTo("#geetest-captcha")
      captchaObj.onSuccess(() => {
        const result = captchaObj.getValidate()
        this.$emit('verified', result)
      })
    })
  }
}
</script>

注意事项

  • 生产环境建议使用专业验证码服务(如reCAPTCHA、极验)
  • 前端生成的验证码需配合服务端会话存储验证
  • 定期更新验证码生成算法防止破解
  • 移动端需考虑触控交互体验

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

相关文章

vue实现博客

vue实现博客

Vue 实现博客的基本步骤 使用 Vue.js 实现一个博客系统可以分为前端和后端两部分。以下是基于 Vue 的前端实现方案,后端可以选择 Node.js、Django 或其他框架。 项目初始化 使…

vue源码实现

vue源码实现

Vue 源码实现解析 Vue.js 的核心实现可以分为响应式系统、虚拟 DOM、模板编译、组件化等几个关键部分。以下是对这些核心机制的详细解析。 响应式系统 Vue 的响应式系统基于 Object.…

vue实现前端录制

vue实现前端录制

Vue 实现前端录制功能 前端录制通常包括音频、视频或屏幕录制,结合Vue框架可以通过浏览器API实现。以下是几种常见录制场景的实现方法: 音频录制 使用浏览器MediaRecorder API实现…

vue实现效果展示

vue实现效果展示

Vue 实现效果展示的方法 动态数据绑定展示 通过 Vue 的响应式特性,实时展示数据变化。例如,表单输入与预览同步: <template> <div> <…

vue cli实现原理

vue cli实现原理

Vue CLI 实现原理 Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统,其核心实现原理可以分为以下几个部分: 核心架构 Vue CLI 采用插件化架构,通过 @vue/cli 提…

vue  全局刷新实现

vue 全局刷新实现

全局刷新实现方法 在Vue中实现全局刷新通常涉及重新加载整个应用或特定路由。以下是几种常见方法: 使用window.location.reload() 强制浏览器重新加载当前页面: window.…