在Vue 3.x项目中高效集成图形验证码可以通过以下步骤实现。我们将使用一个常见的图形验证码库vaptcha
作为示例,但你可以根据需要选择其他库。
首先,你需要安装图形验证码库。以vaptcha
为例:
npm install vaptcha --save
在src/components
目录下创建一个新的组件Captcha.vue
:
<template>
<div id="captcha-container"></div>
</template>
<script>
import { onMounted, onBeforeUnmount } from 'vue';
import vaptcha from 'vaptcha';
export default {
name: 'Captcha',
setup(props, { emit }) {
let vaptchaInstance;
onMounted(() => {
vaptcha({
vid: 'your-vaptcha-id', // 替换为你的Vaptcha ID
container: '#captcha-container',
}).then((instance) => {
vaptchaInstance = instance;
instance.listen('pass', () => {
const token = instance.getToken();
emit('verified', token);
});
});
});
onBeforeUnmount(() => {
if (vaptchaInstance) {
vaptchaInstance.destroy();
}
});
return {};
},
};
</script>
<style scoped>
#captcha-container {
margin: 20px 0;
}
</style>
在登录页面中引入并使用Captcha
组件:
<template>
<div class="login-container">
<form @submit.prevent="handleLogin">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" id="username" v-model="username" required />
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" id="password" v-model="password" required />
</div>
<Captcha @verified="handleCaptchaVerified" />
<button type="submit" :disabled="!isCaptchaVerified">登录</button>
</form>
</div>
</template>
<script>
import { ref } from 'vue';
import Captcha from '@/components/Captcha.vue';
export default {
components: {
Captcha,
},
setup() {
const username = ref('');
const password = ref('');
const isCaptchaVerified = ref(false);
const captchaToken = ref('');
const handleCaptchaVerified = (token) => {
isCaptchaVerified.value = true;
captchaToken.value = token;
};
const handleLogin = () => {
if (isCaptchaVerified.value) {
// 发送登录请求,包含captchaToken
console.log('登录中...', { username: username.value, password: password.value, captchaToken: captchaToken.value });
} else {
alert('请先完成验证码验证');
}
};
return {
username,
password,
isCaptchaVerified,
handleCaptchaVerified,
handleLogin,
};
},
};
</script>
<style scoped>
.login-container {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
</style>
在vaptcha
官网注册并获取vid
,替换Captcha.vue
中的your-vaptcha-id
。
在登录请求中,将captchaToken
发送到后端进行验证。后端需要调用Vaptcha的API来验证captchaToken
的有效性。
运行项目并测试登录流程,确保图形验证码正常工作。
如果你选择其他验证码库(如Google reCAPTCHA),步骤类似,只需替换相应的库和配置即可。
通过以上步骤,你可以在Vue 3.x项目中高效集成图形验证码,提升登录安全性。根据项目需求,你可以选择不同的验证码库,并调整相应的配置和样式。