二、Vue.js 整体接入方案
-
接入步骤
1、组件挂载完成后,动态创建 script 标签加载远程验证码 JS
2、JS 加载完成后,初始化验证码实例,绑定页面 DOM 容器
3、监听验证成功 / 失败 / 刷新事件,接收后端返回的 token
4、表单提交时携带 token,交由后端二次校验
5、组件销毁时清理脚本与实例,避免内存泄漏、路由复用异常
-
核心特性
纯 Vue 原生实现,无额外依赖
路由切换 / 组件销毁自动回收资源,无重复加载、无全局变量污染
下载 Vue.js 接入 Demo
login.vue
<template>
<div class="demo-container">
<h2>KgCaptcha - Vue3 集成演示</h2>
<!-- 登录表单 -->
<div class="form-item">
<input v-model="username" placeholder="请输入账号"/>
</div>
<div class="form-item">
<input v-model="password" placeholder="请输入密码" type="password"/>
</div>
<!-- 验证码容器 -->
<div class="form-item">
<div class="captcha-box-wrapper">
<div id="captchaBox">正在加载验证码...</div>
</div>
</div>
<!-- 登录按钮 -->
<button @click="handleLogin" class="login-btn">
登录
</button>
<!-- 验证码返回的token -->
<div class="captcha-token-info">
验证码Token:{{ captchaToken }}
</div>
</div>
</template>
<script setup>
import {ref, onMounted} from 'vue'
// 表单数据
const username = ref('')
const password = ref('')
const captchaToken = ref('')
// ==============================================
// 加载并初始化凯格验证码(跨域JS)
// ==============================================
onMounted(() => {
// 1. 动态创建 script 标签加载跨域验证码
const script = document.createElement('script')
script.src = 'https://cdn6.kgcaptcha.com/captcha.js?appid=xxxxxx' // 换成你的 appid
script.async = true
// 2. 加载完成后初始化
script.onload = () => {
window.kg.captcha({
bind: '#captchaBox',
// 验证成功
success: (res) => {
console.log('验证成功:', res)
captchaToken.value = res.token // 保存token
},
// 验证失败
failure: (err) => {
console.log('验证失败:', err)
},
// 刷新验证码
refresh: () => {
captchaToken.value = ''
}
})
}
// 3. 把JS加入页面
document.head.appendChild(script)
})
// ==============================================
// 登录方法
// ==============================================
const handleLogin = () => {
if (!captchaToken.value) {
alert('请完成验证')
return
}
console.log('提交登录:', {
username: username.value,
password: password.value,
captcha: captchaToken.value
})
alert('登录成功!验证码token:' + captchaToken.value)
// 此处对接后端接口,后端需校验 captchaToken 有效性
// ...
}
</script>
<style scoped>
h2{
padding: 0 0 20px 0;
}
.demo-container {
width: 400px;
margin: 60px auto;
padding: 30px;
border: 1px solid #eee;
border-radius: 12px;
background: #fff;
}
.form-item {
margin-bottom: 15px;
}
.form-item input {
width: 100%;
height: 40px;
padding: 0 10px;
border: 1px solid #ddd;
border-radius: 6px;
box-sizing: border-box;
}
.login-btn {
width: 100%;
height: 44px;
background: #007bff;
color: #fff;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 16px;
}
.captcha-box-wrapper {
width: 100%;
display: grid;
place-items: center;
padding: 10px 0;
}
.captcha-token-info {
margin-top: 15px;
font-size: 12px;
color: #a9b4d4;
word-break: break-all;
white-space: normal;
overflow-wrap: break-word;
line-height: 1.4;
text-align: center;
}
</style>