产品出设计稿要求做一个仿原生app短信验证码组件,花了两小时搞出来一个还可以的组件,支持屏幕自适应,可以用于弹出框,或自己封装的vue组件里,希望可以帮助那些被产品压榨的同学,哈哈。?
其核心思想就是利用一个输入框使用css3,translate属性,每输入一次后向右位移一个单位位置,直到输入完验证码个数消失。然后定义一个数组smsCodeList,初始化时push对象
smsCodeList = [{
val: '',
isError: ''
}]
// html代码
<div class='sms-check-code-wrapper' @click='handleClick'>
<div class="sms-code-container">
<div :class="['sms-code-title', {'error': error}]"
:style="{'color': error ? errorColor : errorColorDefault}">
{{ title }}</div>
<div class='sms-code-box'>
<div class="sms-code-input-box" :style="{'transform': `translate(${inputBoxActive}%)`}">
<input
ref='refInout'
v-show='isShowInputBox'
type='number'
v-model='inputValue'
class='sms-code-input'
:style="{
'width': style.smsCodeItemWidth + '%',
'paddingLeft': style.inputPL + '%'
}"
@keyup="onKeyUp"
@keydown='onKeyDown'
v-focus
:maxlength='codeNum'
autocomplete="one-time-code"
inputmode="numeric"
value=''
/>
</div>
<div class='sms-code-bottom flex-sb'>
<div class='sms-code-item'
:style="{
'width': style.smsCodeItemWidth + '%'
}"
v-for='(item, index) in smsCodeList' :key='index'>
<span :class="['sms-value', {'error': item.isError }]"
:style="{'color': item.isError ? errorColor : errorColorDefault}">
{{ item.val }}</span>
<span :class="['sms-line', {'error': item.isError}]"
:style="{'backgroundColor': item.isError ? errorColor : errorColorDefault}">
</span>
</div>
</div>
</div>
</div>
</div>
只需简单的这几行html结构,用来渲染标题和输入框和验证码组件
js 代码也很简单
// 首先定义一些初始默认值,因为默认按照6位数验证码来的
let defaultCodeNum = 6
let defaultMoveUnit = 17.2
let defaultInputPL = 7
let defaultSmsCodeItemWidth = 14
export default {
name: "VueSmsCheckCode",
directives: {
focus: {
inserted: function (el) {
el.focus()
}
}
},
props: {
title: {
type: String,
default: '请录入验证码'
},
codeNum: { // 验证码个数
type: Number,
default: 6
},
isError: { // 验证码错误显示错误提示
type: Boolean,
default: false
},
errorColor: {
type: String,
default: '#D81A1A'
}
},
data() {
return {
smsCodeList: [], // 验证码输入显示在div上的数字
inputValue: '', // 输入框的值
smsValue: '', // 验证码完毕后归总的变量
moveUnit: 17.2, // input 位移单位
inputBoxActive: 0, // 当前输入框位移位置
currentIndex: 0, // 当前验证码索引
isShowInputBox: true, // 是否显示输入框
error: false, // 验证码错误报红
errorColorDefault: '#b1b1b1', // 默认错误输入框颜色
style: { // 默认样式
inputPL: 0, // input padding-left值
smsCodeItemWidth: 0, // 验证码显示item的宽度(自适应)
}
}
},
created() {
this.reDomRender() // 初始化时,通过传过来的验证码个数重新渲染组件(各个dom位置,宽度等重新计算)
this.compareList() // push 默认数据
this.inputPaving() // 当点击手机验证码自动填充时,自动平铺数据
},
methods: {
reDomRender() {
this.style = {
inputPL: Math.round(defaultCodeNum / (this.codeNum / defaultInputPL)),
smsCodeItemWidth: Math.round(defaultCodeNum / this.codeNum * defaultSmsCodeItemWidth)
}
this.moveUnit = Math.round(defaultCodeNum / (this.codeNum / (defaultMoveUnit - .3333)))
},
compareList() {
for (let i = 0; i < this.codeNum; i++) {
if (this.smsCodeList.length < this.codeNum) {
this.smsCodeList.push({
val: '',
isError: this.isError
})
}
}
},
initAll() {
this.smsCodeList = []
this.compareList()
this.inputValue = ''
this.smsValue = ''
this.inputBoxActive = 0
this.currentIndex = 0
this.isShowInputBox = true
// 延时解决光标聚焦
setTimeout(() => {
this.$refs.refInout.focus()
})
},
// 当点击验证码时,inputBoxActive,值要分铺在每个输入框里
inputPaving() {
let v = this.inputValue
if (v.length > 0) {
v.split('').forEach((item, index) => {
if (index <= v.length) {
this.smsCodeList[index].val = item
const inputPosition = (index + 1) * this.moveUnit
this.inputBoxActive = inputPosition >= 100 ? 100 : inputPosition
this.currentIndex = index + 1
this.smsValue += item
this.inputValue = ''
if (index + 1 === this.codeNum) {
this.isShowInputBox = false
this.sendFun()
}
}
})
}
},
onKeyDown(e) {
let key = e.key;
e.returnValue = !(key === 'e' || key === 'E' || key === '+' || key === '-');
},
onKeyUp(e) {
if (this.currentIndex < 1) return
if (e.code === 'Backspace' || e.key === 'Backspace') { // 会退
this.currentIndex = this.currentIndex - 1
this.inputBoxActive = this.inputBoxActive - this.moveUnit
this.smsCodeList = this.smsCodeList.map((val, index) => {
if (index === this.currentIndex) {
val.val = ''
val.isError = this.isError
return val
}
return val
})
}
},
handleClick() {
this.$refs.refInout.focus()
},
sendFun() {
this.$emit('finish', this.smsValue)
}
},
watch: {
inputValue(v) { // 监听输入框输入的值
if (!v) return
// 初始化时,点击软键盘上的验证码自动填充时分铺input数据
if (v.length > 1) {
this.inputPaving()
return;
}
this.inputBoxActive = this.inputBoxActive + this.moveUnit
this.smsCodeList.map((val, index) => {
if (this.currentIndex === index) {
if(val) {
//当前输入的位置使红色底部条初始化
val.isError = false
}
val.val = v
return val
}
return val
})
this.currentIndex += 1
this.inputValue = ''
if (this.currentIndex >= this.codeNum) { // 当最后一位时发
this.isShowInputBox = false
this.smsCodeList.forEach(val => {
this.smsValue += val.val
})
this.sendFun()
}
},
isError(v) { // 监听验证码是否错误
this.error = v
if (v) {
this.smsCodeList.map(value => {
value.isError = true
return value
})
this.initAll()
}
}
}
}
剩下的就是css了
npm install vue-sms-check-code --save
最新版1.0.1 (2022/5/25)
包常规操作下载使用
另外需要完整的代码请到github或gitee上下载
开源并总结整理真的很费时间,如果不错还请star
?️问题请issues
源码里有example 使用方式,使用灰常简单。
开源并总结整理真的很费时间,欢迎star
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:
当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested
我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie