Vue Js CAPTCHA Generator: Creating a custom CAPTCHA generator using vanilla JavaScript in Vue.js can be a fun and useful exercise. CAPTCHA stands for Completely Automated Public Turing test to tell Computers and Humans Apart, and it is a challenge-response test that is used to determine whether the user is a human or a bot. A CAPTCHA typically consists of an image with some distorted text or characters that the user needs to identify and enter correctly to prove their humanity.In this tutorial, we will learn how to build a personalized CAPTCHA generator utilizing vanilla JavaScript within Vue.js.
How to Create Custom Vue Js CAPTCHA generator?
The generateCaptcha()
function creates a captcha code by selecting characters from a given set of characters, and adding some visual distortion.
The chars
variable contains the characters that will be used to create the captcha, and the captchaChars
array will hold the final captcha code.
The function then enters a loop that will run 6 times, to select 6 random characters from chars
. For each character, the function also selects a random font size between 20 and 30 and a random rotation between -10 and 10 degrees.
The selected character, font size, and rotation are added to the captchaChars
array as an object, with properties char
, fontSize
, and rotation
.
Finally, the captchaChars
array is assigned to the this.captchaChars
property, which can be used to display the captcha in a UI.
Vue Js CAPTCHA Generator Example
<div id="app">
<div class="captcha">
<template v-for="(char, index) in captchaChars">
<span class="captcha-char" :key="index"
:style="{ fontSize: char.fontSize + 'px', transform: 'rotate(' + char.rotation + 'deg)' }">
{{ char.char }}
</span>
</template>
</div>
<button class="btn" @click="generateCaptcha">Refresh</button>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
captchaChars: [],
characters: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
}
},
mounted() {
this.generateCaptcha();
},
methods: {
generateCaptcha() {
const chars = this.characters.split('');
let captchaChars = [];
for (let i = 0; i < 6; i++) {
let char = chars[Math.floor(Math.random() * chars.length)];
let fontSize = Math.floor(Math.random() * 10) + 20; // random font size between 20 and 30
let rotation = Math.floor(Math.random() * 21) - 10; // random rotation between -10 and 10 degrees
captchaChars.push({ char, fontSize, rotation });
}
this.captchaChars = captchaChars;
},
},
});
app.mount('#app');
</script>