当前位置:首页 > VUE

验证码实现vue

2026-02-25 14:43:27VUE

验证码实现(Vue.js)

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

安装 vaptchavue-captcha 等专用库:

npm install vue-captcha --save

组件引入示例:

<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>

服务端验证方案

前端调用示例:

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 })
  }
})

滑动验证码集成

使用第三方服务如极验:

验证码实现vue

<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 实现安全免登录的方案 免登录功能通常通过持久化认证状态(如 Token)实现,但需兼顾安全性。以下是基于 Vue 的常见实现方案: 基于 Token 的免登录 登录成功后存储 Token…

vue 实现直播

vue 实现直播

Vue 实现直播的基本方法 在Vue中实现直播功能,通常需要结合WebRTC、RTMP或HLS等技术。以下是几种常见的实现方式: 使用WebRTC实现实时直播 WebRTC适合低延迟的实时直播场景,…

vue实现hover

vue实现hover

Vue 实现 hover 效果的方法 在 Vue 中实现 hover 效果可以通过多种方式实现,包括使用 CSS、Vue 指令或事件监听。以下是几种常见的方法: 使用 CSS :hover 伪类 通…

vue实现oauth

vue实现oauth

Vue 实现 OAuth 的步骤 安装必要的依赖 确保项目中安装了 axios 和 vue-router。OAuth 通常需要发送 HTTP 请求和处理路由跳转。 npm install axios…

vue 实现表单

vue 实现表单

Vue 表单实现方法 Vue.js 提供了多种方式实现表单,包括双向数据绑定、表单验证和动态表单生成。以下是常见的实现方法: 基础表单绑定 使用 v-model 指令实现表单元素与数据的双向绑定:…

vue实现必填

vue实现必填

Vue 实现表单必填验证的方法 在Vue中实现表单必填验证可以通过多种方式完成,以下是几种常见的方法: 使用HTML5原生属性 最简单的必填验证可以通过HTML5的required属性实现: &l…