<template>
<div>
<input v-model="captcha" placeholder="请输入验证码" />
<img :src="captchaImage" @click="refreshCaptcha" alt="验证码图片" />
<button @click="verifyCaptcha">验证</button>
</div>
</template>
<script>
export default {
data() {
return {
captcha: '',
captchaImage: '/api/captcha' // 假设后端提供了一个获取验证码图片的API
};
},
methods: {
refreshCaptcha() {
// 每次点击刷新验证码,通过添加时间戳防止浏览器缓存
this.captchaImage = `/api/captcha?t=${new Date().getTime()}`;
},
verifyCaptcha() {
// 发送验证码到后端进行验证
this.$axios.post('/api/verify', { captcha: this.captcha })
.then(response => {
if (response.data.success) {
alert('验证码正确');
} else {
alert('验证码错误');
this.refreshCaptcha(); // 验证失败刷新验证码
}
})
.catch(error => {
console.error('验证失败:', error);
});
}
}
};
</script>
<style scoped>
/* 样式可以根据需要自行调整 */
</style>
模板部分 (<template>):
<input>) 用于用户输入验证码。<img> 标签用于显示验证码图片,点击图片会刷新验证码。<button>) 用于触发验证码验证。脚本部分 (<script>):
data 中定义了两个属性:captcha 用于存储用户输入的验证码,captchaImage 用于存储验证码图片的URL。methods 中定义了两个方法:refreshCaptcha: 点击图片时调用,通过在URL后面添加时间戳来刷新验证码图片,防止浏览器缓存。verifyCaptcha: 点击验证按钮时调用,发送用户输入的验证码到后端进行验证,并根据返回结果提示用户验证码是否正确。如果验证失败,则刷新验证码。样式部分 (<style scoped>):
希望这个示例能帮助你理解如何在 Vue 中实现验证码功能。
上一篇:vue3定义数组
下一篇:vue3 slot 传值
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站