封装手机验证登录组件
简单封装手机验证登录组件,全局注册,利用element-ui库
如图:
定义phoneLogin.vue组件
<template> <div> <el-form :model="ruleForm" :rules="rules" ref="ruleForm"> <el-form-item prop="phone"> <el-input placeholder="请输入手机号" v-model="ruleForm.phone"> <i slot="prefix" class="el-icon-phone"></i> </el-input> </el-form-item> <el-form-item prop="code"> <el-row :gutter="18"> <el-col :span="18"> <el-input placeholder="请输入验证码" v-model="ruleForm.code"> <i slot="prefix" class="el-icon-tickets"></i> </el-input> </el-col> <el-col :span="6"> <el-button @click="sendCode" :disabled="disabled">{{ this.btnText }}</el-button> </el-col> </el-row> </el-form-item> <el-form-item> <el-button type="primary" style="100%" @click="phoneLogin">登录</el-button> </el-form-item> </el-form> </div> </template> <script> export default { name: "PhoneLogin", components: {}, props: { ruleForm: { type: Object, required: true, }, countDown: { type: Number, default: 60, }, }, data() { let checkPhone = (rule, value, callback) => { if (!value) { return callback(new Error("手机号不能为空")); } else { let reg = /^1[3|4|5|7|8][0-9]d{8}$/; if (reg.test(value)) { callback(); } else { return callback(new Error("请输入正确的手机号")); } } }; return { rules: { phone: [ { validator: checkPhone, trigger: "change", }, ], code: [ { required: true, message: "验证码不能为空", trigger: "blur", }, ], }, disabled: false, btnText: "发送验证码", time: 0, }; }, methods: { sendCode() { this.$refs.ruleForm.validateField("phone", (errorMessage) => { if (errorMessage) { this.$message.error(errorMessage); } else { let timer = setInterval(() => { this.time--; this.btnText = `${this.time}s后重新发送`; this.disabled = true; if (this.time === 0) { this.disabled = false; this.btnText = "重新发送"; this.time = this.countDown; clearInterval(timer); } }, 1000); this.$emit("send"); } }); }, phoneLogin(){ this.$refs.ruleForm.validate((valid)=>{ if(valid){ this.$emit('submit') }else{ this.$emit('errHand') } }) } }, mounted() { this.time = this.countDown; }, }; </script>
注册公共组件
import Vue from "vue" import PhoneLogin from "../components/PhoneLogin" Vue.component('PhoneLogin',PhoneLogin)
在view页面引用
<template> <div> <h1>短信验证码登录</h1> <PhoneLogin :rule-form="PhoneForm" @send="send" @submit="submit" @errHandle="errHandle"></PhoneLogin> </div> </template> <script> export default { name: "LoginPage", components: {}, props: {}, data() { return { PhoneForm: { phone: "", code: "", }; }, methods: { submit() { this.$message.success("提交成功"); }, errHandle() { this.$message.error("表单错误"); }, send() { this.$message.info("发送验证码成功"); }, }, }; </script>