经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
vue实现手机验证码登录
来源:jb51  时间:2021/11/22 13:41:47  对本文有异议

本文实例为大家分享了vue实现手机验证码登录的具体代码,供大家参考,具体内容如下

验证码

  1. <template>
  2. <div>
  3. <el-main>
  4. <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  5. <el-form-item label="手机号" prop="phone">
  6. <el-input v-model="ruleForm.phone" placeholder="请输入手机号" size=""
  7. maxlength="11"></el-input>
  8. </el-form-item>
  9.  
  10. <el-form-item label="验证码" prop="code">
  11. <el-row :span="24">
  12. <el-col :span="12">
  13. <el-input v-model="ruleForm.code" auto-complete="off" placeholder="请输入验证码" size=""
  14. maxlength="4"
  15. @keyup.enter.native="submitForm('ruleForm')"></el-input>
  16. </el-col>
  17. <el-col :span="12">
  18. <div class="login-code">
  19. <!--验证码组件-->
  20. <el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}"
  21. :disabled="getCodeBtnDisable">{{ codeBtnWord }}
  22. </el-button>
  23. </div>
  24. </el-col>
  25. </el-row>
  26. </el-form-item>
  27.  
  28. <!--滑动验证组件-->
  29. <Verify></Verify>
  30.  
  31. <el-form-item>
  32. <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
  33. </el-form-item>
  34. </el-form>
  35.  
  36. </el-main>
  37. </div>
  38. </template>

用到的vue验证工具类

  1. export default {
  2. // 限制只能输入数字(可以输入两位小数点)
  3. limitInputPointNumber(val) {
  4. if (val === 0 || val === "0" || val === "" || val === undefined) {
  5. return "";
  6. } else {
  7. let value = null;
  8. value = val.replace(/[^\d.]/g, ""); // 清除“数字”和“.”以外的字符
  9. value = value.replace(/\.{2,}/g, "."); // 只保留第一个. 清除多余的
  10. value = value
  11. .replace(".", "$#$")
  12. .replace(/\./g, "")
  13. .replace("$#$", ".");
  14. value = value.replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
  15. return value;
  16. }
  17. },
  18.  
  19. handleRouteToArray(route) {
  20. const matchs = route.path.split('/')
  21. matchs.shift()
  22. let newMatch = []
  23. matchs.map((item, i) => {
  24. if (matchs[i - 1]) {
  25. item = newMatch[i - 1] + '/' + item
  26. }
  27. newMatch.push(item)
  28. })
  29. newMatch = newMatch.map(item => {
  30. return `/${item}`
  31. })
  32. return newMatch
  33. },
  34.  
  35. // 密码长度8位以上,须包含大写、小写、数字、特殊符号中的任意3种
  36. testPassWord: function (str) {
  37. var rC = {
  38. lW: '[a-z]',
  39. uW: '[A-Z]',
  40. nW: '[0-9]',
  41. sW: '[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]'
  42. }
  43. function Reg (str, rStr) {
  44. var reg = new RegExp(rStr)
  45. if (reg.test(str)) return true
  46. else return false
  47. }
  48. if (str.length < 8) {
  49. return false
  50. } else {
  51. var tR = {
  52. l: Reg(str, rC.lW),
  53. u: Reg(str, rC.uW),
  54. n: Reg(str, rC.nW),
  55. s: Reg(str, rC.sW)
  56. }
  57. if ((tR.l && tR.u && tR.n) || (tR.l && tR.u && tR.s) || (tR.s && tR.u && tR.n) || (tR.s && tR.l && tR.n)) {
  58. // document.title = "密码符合要求"
  59. return true
  60. } else {
  61. return false
  62. }
  63. }
  64. },
  65.  
  66. // 密码验证8-30位任意字符
  67. pwdReg: /^([0-9a-zA-Z]|(?:&)|(?:~)|(?:!)|(?:@)|(?:#)|(?:\$)|(?:%)|(?:\^)|(?:\*)){8,30}$/,
  68.  
  69. // 电话号码验证
  70. phoneReg: /^1[3|4|5|6|7|8][0-9]{9}$/,
  71.  
  72. // 格式化金钱
  73. formatUSD (val, currency) {
  74. if (val === '' || val === '--' || val === undefined) {
  75. return '--'
  76. }
  77. // 先判断数据是否有小数点
  78. let newVal = String(Number(val).toFixed(2))
  79. // 将科学计数转为正常的字符串显示
  80. if (newVal.includes('e+')) {
  81. newVal = Number(newVal).toLocaleString()
  82. newVal = this.unFormatAmount(newVal)
  83. }
  84. let dotIdx = newVal.lastIndexOf('.')
  85. let dotVal = '.00' // 保留小数点后面的数据
  86. if (dotIdx >= 0) {
  87. dotVal = newVal.substr(dotIdx, newVal.length)
  88. newVal = newVal.slice(0, dotIdx)
  89. }
  90.  
  91. let len = newVal.length
  92. let arr = []
  93. let lastIndex = null
  94. while (len > 0) {
  95. lastIndex = len
  96. len -= 3
  97. arr.unshift(newVal.substring(len, lastIndex))
  98. }
  99. val = arr.join(',')
  100.  
  101. if (currency) {
  102. newVal = `${currency} ${val}${dotVal}`
  103. } else {
  104. // newVal = `$ ${val}${dotVal}`
  105. newVal = `¥ ${val}${dotVal}` // 默认人民币
  106. }
  107. return newVal
  108. },
  109.  
  110. // 格式化金额数字,不包含小数点,金额符等 输入整数
  111. formatAmount (val) {
  112. if (val === '' || val === '--' || val === undefined) {
  113. return '--'
  114. }
  115. if (val === 0 || val === '0') {
  116. return 0
  117. }
  118. // 先判断数据是否有小数点
  119. let newVal = String(val)
  120. let dotIdx = newVal.lastIndexOf('.')
  121. let dotLength = 0
  122. if (newVal.split('.').length > 1) {
  123. dotLength = newVal.split('.')[1].length
  124. }
  125. let dotVal = '' // 保留小数点后面的数据
  126. if (dotIdx >= 0) {
  127. newVal = String(Number(val).toFixed(5))
  128. dotVal = newVal.substr(dotIdx, dotLength + 1)
  129. newVal = newVal.slice(0, dotIdx)
  130. }
  131. let len = newVal.length
  132. let arr = []
  133. let lastIndex = null
  134. while (len > 0) {
  135. lastIndex = len
  136. len -= 3
  137. arr.unshift(newVal.substring(len, lastIndex))
  138. }
  139. val = arr.join(',')
  140. if (dotVal.length < 2) {
  141. dotVal = ''
  142. }
  143. return val + dotVal
  144. },
  145.  
  146. // 判断数据是否为空
  147. isEmptyVal (val) {
  148. if (val === undefined || val === '') {
  149. return '--'
  150. } else {
  151. return val
  152. }
  153. },
  154.  
  155. // 格式化年月日 type: 中国显示方式(ch)及拼接的方式
  156. // 注: 只有在接口传参时才需要中国的显示方式,其它为美式
  157. formatYMD (now, type='ch') {
  158. if (!now || now === 'null' || now === '--' || now === undefined) {
  159. return '--'
  160. }
  161. if (Number(now)) {
  162. now = new Date(now)
  163. }
  164. // 兼容IE浏览器 , YY-MM-DD 格式
  165. if (typeof now === 'string' && now.includes('-')) {
  166. now = this.NewDate(now)
  167. }
  168. if (now) {
  169. let year = ''
  170. let month = ''
  171. let date = ''
  172. // 这里的8位用于返回如 20180423 这样的格式
  173. if (String(now).length === 8 && String(now).indexOf('-') === -1 && String(now).indexOf('/') === -1) {
  174. const getNow = String(now)
  175. return `${getNow.substring(4, 6)}/${getNow.substring(6, 8)}/${getNow.substring(0, 4)}`
  176. } else {
  177. now = new Date(now)
  178. year = now.getFullYear()
  179. month = now.getMonth() + 1
  180. date = now.getDate()
  181. }
  182. if (month < 10) {
  183. month = `0${month}`
  184. }
  185. if (date < 10) {
  186. date = `0${date}`
  187. }
  188. if (type === 'ch') {
  189. return `${year}-${month}-${date}`
  190. } else if (type) {
  191. return `${year}${type}${month}${type}${date}`
  192. } else {
  193. return `${month}/${date}/${year}`
  194. }
  195. } else {
  196. return ''
  197. }
  198. },
  199.  
  200. // 格式化时间 年,月,日,时,分,秒
  201. formatDate (now, type) {
  202. if (!now || now === 'null' || now === '--' || now === undefined) {
  203. return '--'
  204. }
  205. if (now) {
  206. now = new Date(now)
  207. let year = now.getFullYear()
  208. let month = now.getMonth() + 1
  209. let date = now.getDate()
  210. let hour = now.getHours()
  211. let minute = now.getMinutes()
  212. let second = now.getSeconds()
  213. if (month < 10) {
  214. month = `0${month}`
  215. }
  216. if (date < 10) {
  217. date = `0${date}`
  218. }
  219. if (hour < 10) {
  220. hour = `0${hour}`
  221. }
  222. if (minute < 10) {
  223. minute = `0${minute}`
  224. }
  225. if (second < 10) {
  226. second = `0${second}`
  227. }
  228. if (type) {
  229. return `${month}/${date}/${year} ${hour}:${minute}:${second}`
  230. } else {
  231. return `${month}-${date}-${year}`
  232. }
  233. } else {
  234. return ''
  235. }
  236. },
  237. }

直接放上完整的这样有助于看

  1. <template>
  2. <div>
  3. <el-main>
  4. <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  5. <el-form-item label="手机号" prop="phone">
  6. <el-input v-model="ruleForm.phone" placeholder="请输入手机号" size=""
  7. maxlength="11"></el-input>
  8. </el-form-item>
  9.  
  10. <el-form-item label="验证码" prop="code">
  11. <el-row :span="24">
  12. <el-col :span="12">
  13. <el-input v-model="ruleForm.code" auto-complete="off" placeholder="请输入验证码" size=""
  14. maxlength="4"
  15. @keyup.enter.native="submitForm('ruleForm')"></el-input>
  16. </el-col>
  17. <el-col :span="12">
  18. <div class="login-code">
  19. <!--验证码组件-->
  20. <el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}"
  21. :disabled="getCodeBtnDisable">{{ codeBtnWord }}
  22. </el-button>
  23. </div>
  24. </el-col>
  25. </el-row>
  26. </el-form-item>
  27.  
  28. <!--滑动验证组件-->
  29. <Verify></Verify>
  30.  
  31. <el-form-item>
  32. <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
  33. </el-form-item>
  34. </el-form>
  35.  
  36. </el-main>
  37. </div>
  38. </template>
  39.  
  40. <script>
  41. //导入工具类
  42. import Verify from "@/components/Verify";
  43. import event from "../utils/event"
  44. import common from "@/utils/common";
  45.  
  46. let params;
  47. export default {
  48. name: "LoginIphone",
  49. components: {Verify},
  50. data() {
  51. //使用正则表达式验证手机号
  52. const checkPhone = (rule, value, callback) => {
  53. if (!value) {
  54. return callback(new Error('手机号不能为空'));
  55. } else {
  56. //获取工具类中的手机号正则表达式
  57. const reg = common.phoneReg
  58. // console.log(reg.test(value));
  59. if (reg.test(value)) {
  60. callback();
  61. } else {
  62. //如果验证输入错误就清空
  63. this.ruleForm.phone = ''
  64. return callback(new Error('请输入正确的手机号'));
  65. }
  66. }
  67. };
  68.  
  69. return {
  70. ruleForm: {
  71. phone: '',
  72. code: '',
  73. },
  74.  
  75. codeBtnWord: '获取验证码', // 获取验证码按钮文字
  76. // waitTime: 61, // 获取验证码按钮失效时间
  77. waitTime: 2, // 获取验证码按钮失效时间
  78. // 校验
  79. rules: {
  80. phone: [
  81. {validator: checkPhone, trigger: 'blur'}
  82. ],
  83. code: [
  84. {required: true, message: '请输入验证密码', trigger: 'blur'}
  85. ]
  86. }
  87. };
  88. },
  89. //计算属性computed
  90. computed: {
  91. // 控制获取验证码按钮是否可点击
  92. getCodeBtnDisable: {
  93. //设置按钮61s
  94. // get() {
  95. // if (this.waitTime === 61) {
  96. // if (this.ruleForm.phone) {
  97. // return false
  98. // }
  99. // return true
  100. // }
  101. // return true
  102. // }
  103. get() {
  104. if (this.waitTime === 2) {
  105. if (this.ruleForm.phone) {
  106. return false
  107. }
  108. return true
  109. }
  110. return true
  111. },
  112. // 注意:因为计算属性本身没有set方法,不支持在方法中进行修改,而下面我要进行这个操作,所以需要手动添加
  113. set() {
  114. }
  115. },
  116.  
  117. }, methods: {
  118.  
  119. getCode() {
  120. const _this = this
  121. params = {}
  122. params.phone = this.ruleForm.phone
  123. // 调用获取短信验证码接口
  124. _this.$axios.post('/sendMessage', params).then(res => {
  125. console.log("--------查看后台响应的值-----", res)
  126. //把所有的数据存在
  127. const mydata = res.data.data
  128. console.log("我在短信接口这利-->", mydata)
  129.  
  130. //保存验证码
  131. params.yz = mydata.vCode
  132.  
  133. console.log("我是查看验证码-------" + mydata.vCode)
  134. console.log("我是查看调用的次数-------" + mydata.count)
  135.  
  136. if (res.data.code === 200) {
  137. this.$message({
  138. message: '验证码已发送,请稍候...',
  139. type: 'success',
  140. center: true
  141. })
  142. }
  143. if (res.data.data.count >= 5) {
  144. //调用滑块验证的组件
  145. event.$emit("VERIFY")
  146. }
  147.  
  148. })
  149.  
  150. // 因为下面用到了定时器,需要保存this指向
  151. let that = this
  152. that.waitTime--
  153. that.getCodeBtnDisable = true
  154. this.codeBtnWord = `${this.waitTime}s 后重新获取`
  155. let timer = setInterval(function () {
  156. if (that.waitTime > 1) {
  157. that.waitTime--
  158. that.codeBtnWord = `${that.waitTime}s 后重新获取`
  159. } else {
  160. clearInterval(timer)
  161. that.codeBtnWord = '获取验证码'
  162. that.getCodeBtnDisable = false
  163. // that.waitTime = 61
  164. that.waitTime = 2
  165. }
  166. }, 1000)
  167. },
  168. submitForm(formName) {
  169. const _this = this
  170. //判断输入的验证码是否为空
  171. if (this.ruleForm.code != null) {
  172. this.$refs[formName].validate((valid) => {
  173. if (valid) {
  174.  
  175. _this.$axios.post("/iosLogin", {
  176. "phone": this.ruleForm.phone,
  177. "Verification": this.ruleForm.code
  178. }).then(res => {
  179.  
  180. console.log(res.data)
  181. })
  182.  
  183.  
  184. // console.log("我是提交里面的:", par)
  185. //
  186. // const jwt = par.headers['authorization']
  187. // console.log("我是token->", jwt)
  188. // const userInfo = par.data.data
  189. // console.log("查看用户信息=", userInfo)
  190. //
  191. // // 把数据共享出去
  192. // _this.$store.commit("SET_TOKEN", jwt)
  193. // _this.$store.commit("SET_USERINFO", userInfo)
  194. //
  195. // // 获取
  196. // console.log("我是获取的_this.$store.getters.getUser")
  197. // console.log(_this.$store.getters.getUser)
  198.  
  199. // _this.$router.push("/blogs")
  200.  
  201. } else {
  202. console.log('error submit!!');
  203. return false;
  204. }
  205. });
  206. } else {
  207. this.$message({
  208. showClose: true,
  209. message: '请输入错误',
  210. type: 'error'
  211. });
  212. }
  213. }
  214.  
  215. }
  216.  
  217. }
  218. </script>
  219. <style scoped>
  220. .el-button.disabled-style {
  221. background-color: #EEEEEE;
  222. color: #CCCCCC;
  223. }
  224.  
  225. .demo-ruleForm {
  226. max-width: 500px;
  227. margin: 0 auto;
  228. }
  229. </style>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号