js/vue实现滑块验证(组件形式,可重复调用)(方法2)
子组件中代码如下:
<template> <div class="jc-component__range"> <div class="jc-range" :class="rangeStatus?'success':''" > <div class="backbg"></div> <i @mousedown="rangeMove" :class="rangeStatus?successIcon:startIcon"></i> <div>{{rangeStatus?successText:startText}}</div> </div> </div> </template> <script> export default { props: { // 成功之后的函数 successFun: { type: Function }, //成功图标 successIcon: { type: String, default: 'el-icon-success' }, //成功文字 successText: { type: String, default: '验证成功' }, //开始的图标 startIcon: { type: String, default: 'el-icon-d-arrow-right' }, //开始的文字 startText: { type: String, default: '请拖住滑块,拖动到最右边' }, //失败之后的函数 errorFun: { type: Function }, //或者用值来进行监听 status: { type: String } }, data(){ return { disX : 0, rangeStatus: false } }, methods:{ //滑块移动 rangeMove(e){ let ele = e.target; let startX = e.clientX; let eleWidth = ele.offsetWidth; let parentWidth = ele.parentElement.offsetWidth; let MaxX = parentWidth - eleWidth; let leftBox = document.getElementsByClassName('backbg')[0]; if(this.rangeStatus){//不运行 return false; } document.onmousemove = (e) => { let endX = e.clientX; this.disX = endX - startX; if(this.disX<=0){ this.disX = 0; } if(this.disX>=MaxX-eleWidth){//减去滑块的宽度,体验效果更好 this.disX = MaxX; } ele.style.transition = '.1s all'; ele.style.transform = 'translateX('+this.disX+'px)'; e.preventDefault(); } document.onmouseup = ()=> { leftBox.style.width = 0+'px' leftBox.style.transition = '.5s all'; if(this.disX !== MaxX){ ele.style.transition = '.5s all'; ele.style.transform = 'translateX(0)'; //执行成功的函数 this.errorFun && this.errorFun(); }else{ this.rangeStatus = true; if(this.status){ this.$parent[this.status] = true; } //执行成功的函数 this.successFun && this.successFun(); } document.onmousemove = null; document.onmouseup = null; } } } }; </script> <style lang="scss" scoped> @mixin jc-flex{ display: flex; justify-content: center; align-items: center; } .backbg{ width: 0; height: 100%; background-color: #4092ff; position: absolute; left: 0; } .jc-component__range{ .jc-range{ background-color: #e9e9e9; position: relative; transition: 1s all; user-select: none; color: #585858; @include jc-flex; height: 50px; /*no*/ &.success{ background-color: #4092ff; color: #fff; i{ color: #4092ff; } } i{ position: absolute; left: 0; width: 40px;/*no*/ height: 98%; color: #4092ff; background-color: #fff; border: 1px solid #d8d8d8; cursor: pointer; font-size: 24px; @include jc-flex; } } } </style>
父组件调用:
<JcRange :successFun="onMpanelSuccess" :errorFun="onMpanelError"></JcRange>
引入子组件:
import JcRange from "@/components/JcRange.vue";
components: {
JcRange
},
父组件写成功回调和失败回调:
onMpanelSuccess(){
},
onMpanelError(){
},
若滑块需多次调用(如更新信息时,为防止恶意调接口,则每次更新信息都进行滑块验证),可使用v-if控制显示隐藏
<div v-if="showUpdatVerify">
<JcRange :successFun="onMpanelSuccess" :errorFun="onMpanelError"></JcRange>
</div>
效果如下:
(未拖动)
(拖动中)
(验证成功)
参考链接:https://blog.csdn.net/qq_43487181/article/details/94143663