1、思路
1、在登录页面需要启动向右滑块验证
2、效果图
3、文章地址:滑动验证码的实现-vue-simple-verify
2、成分分析
1、由三块构成,分别是底部条、拖动条、拖动移动部分
2、底部条:整体容器,包括背景、边框和文字(请按住滑块,拖动到最右边)
3、拖动条:图片+边框+背景色即可
4、完成部分:背景、边框和文字(验证完成)
3、事件分析
1、鼠标按下事件:记录鼠标位置以及状态
2、鼠标移动事件:计算滑块位置
3、鼠标离开事件:更新状态至初始状态
4、鼠标抬起事件:更新状态至初始状态
4、效果图
5、代码
1、SlideVerify.vue文件
<template><divref="sliderContainer"@mousemove="onMouseMove"@mouseup="onMouseUp"class="slider-verify-container"@mouseleave="onMouseLeave"><span v-if="blockState === 0">请按住滑块,拖动到最右边</span><div@mousedown="onMouseDown":style="{ left: leftP }"class="slider-verify-block"/><div :style="{ width: leftP }" class="slider-verify-complete"><span v-if="blockState === 2">验证成功</span></div></div>
</template><script setup>
import { ref, defineEmits } from "vue";const emit = defineEmits(["success", "failed"]);const leftP = ref("0");const blockState = ref(0);const startP = ref(undefined);const sliderContainer = ref(undefined);
const onMouseDown = (e) => {if (blockState.value !== 2) {leftP.value = "0";blockState.value = 1;startP.value = {clientX: e.clientX,};} else {leftP.value = "0";blockState.value = 0;}
};
const onMouseMove = (e) => {if (blockState.value === 1) {let width = e.clientX - startP.value.clientX;if (width + 56 > 400) {leftP.value = 400 - 56 + "px";blockState.value = 2;emit("success");} else {leftP.value = width + "px";}}
};
const onMouseUp = (e) => {if (blockState.value !== 2) {leftP.value = "0";blockState.value = 0;emit("failed");}
};
const onMouseLeave = (e) => {if (blockState.value !== 2) {leftP.value = "0";blockState.value = 0;emit("failed");}
};
</script><style lang="scss" scoped>
.slider-verify-container {width: 100%;height: 56px;background-color: transparent;position: relative;border: solid 1px #20cccf;text-align: center;color: #20cccf;line-height: 56px;user-select: none;-moz-user-select: none;-ms-user-select: none;-webkit-user-select: none;
}
.slider-verify-complete {width: 0;height: 56px;position: absolute;background-color: #00e6f14f;left: 0;top: 0;
}
.slider-verify-block {width: 56px;height: 56px;background-image: url("@/assets/images/login6/arrow.png");background-color: white;position: absolute;left: 0;top: -1px;border: solid 1px #20cccf;background-size: 50%;background-repeat: no-repeat;background-position: center;
}
</style>
2、调用代码
<slide-verify @success="onVerifySuccess" @failed="onVerifyFailed" />