Vue3封装登录功能的两种实现

目录
  • 方法一:使用用户名和密码进行登录
  • 方法二:使用手机验证码登录

方法一: 使用用户名和密码进行登录

封装代码:

<template>
  <el-form
      ref="ruleFormRef"
      status-icon
      :model="ruleForms"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
  >
    <el-form-item label="用户名:" prop="username">
      <el-input v-model="ruleForms.username" autocomplete="off">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user/>
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input type="password" v-model="ruleForms.password" placeholder="Type something">
        <template #prefix>
          <el-icon class="el-input__icon">
            <search/>
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleLogin">Submit</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {User, Search} from '@element-plus/icons-vue'
import {defineProps, reactive, ref, defineEmits, onMounted, watch} from 'vue'

let ruleForms = reactive({username: '', password: ''})
const ruleFormRef = ref(null)
const emits = defineEmits(['onSubmit', 'onError'])

const props = defineProps({
  ruleForm: {
    type: Object,
    required: true
  },
  rules: {
    type: Object,
    required: true
  }
})

onMounted(() => {
  ruleForms = props.ruleForm
})

watch(
    () => props.ruleForm,
    val => {
      ruleForms = val
    },
    {immediate: true}
)

// 登录功能
const handleLogin = () => {
  ruleFormRef.value.validate(valid => {
    if (valid) {
      emits('onSubmit')
    } else {
      emits('onError')
    }
  })
}
</script>

<style scoped>

</style>

使用:

<template>
  <div class="login">

    <div class="account-panel">
      <account-login
          :ruleForm="ruleForm"
          :rules="rules"
          @onSubmit="onSubmit"
          @onError="onError"
      />
    </div>
  </div>
</template>

<script setup>
import {reactive} from 'vue'
import {ElMessage} from 'element-plus'

const ruleForm = reactive({
  username: '',
  password: ''
})
const rules = reactive({
  username: [
    {
      required: true,
      trigger: 'blur',
      message: '用户名长度在2-6之间'
    }
  ],
  password: [
    {
      required: true,
      trigger: 'blur',
      validator: '密码不能为空'
    }
  ]
})
const onSubmit = () => {
  alert('发送 http请求:')
  ElMessage({
    type: 'success',
    message: '保存成功'
  })
}
const onError = () => {
  ElMessage({
    type: 'warning',
    message: '校验失败'
  })
}

</script>

<style scoped lang="scss">
.login {
  margin-top: 50px;
  margin-left: 20px;
}

.account-panel {
  width: 350px;
  height: 350px;
}
</style>

方法二: 使用手机验证码登录

封装代码:

<template>
  <div>
    <el-form :model="rulesForm" :rules="rules" ref="rulesRef">
      <el-form-item label="手机号:" prop="phone">
        <el-input v-model="rulesForm.phone" placeholder="请输入手机号">
        </el-input>
      </el-form-item>
      <el-form-item label="验证码:" prop="countDown">
        <el-row :gutter="24">
          <el-col :span="18">
            <el-input v-model="rulesForm.countDown" placeholder="验证码"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button @click="sendCode" :disabled="disabled">{{ btnText }}</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin">Submit</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import {defineProps, ref, reactive, watch, defineEmits} from 'vue'
import {ElMessage} from "element-plus";

const 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('请输入正确的手机号!'))
    }
  }
}

const rulesForm = ref({})
const disabled = ref(false)
const btnText = ref('发送验证码')

const props = defineProps({
  ruleForm: {
    type: Object,
    required: true
  },
  countDown: {
    type: Number,
    required: true
  }
})
const emits = defineEmits(['sendCode'])
const rules = reactive({
  phone: [{required: true, trigger: 'change', validator: checkPhone,}],
  countDown: [{required: true, message: '验证码不能为空'}]
})
const rulesRef = ref(null)
const time = ref(0) // 设置倒计时

// 发送验证码
const sendCode = () => {
  // 手机号必须输入正确,如果不正确,就提示
  rulesRef.value.validateField('phone', errMessage => {
    if (!errMessage) {
      ElMessage({
        type: 'error',
        message: '请输入正确的手机号'
      })
    } else {
      // 1、时间开始倒数
      // 2、按钮进入禁用状态
      // 3、如果倒计时结束,按钮恢复可用状态,按钮文字变成重新发送
      // 4、倒计时的过程中,按钮文字为多少秒后重新发送
      time.value = props.countDown
      let timer = setInterval(() => {
        time.value--
        btnText.value = `${time.value}s后重新发送`
        disabled.value = true
        if (time.value === 0) {
          disabled.value = false
          btnText.value = '重新发送'
          time.value = props.countDown
          clearInterval(timer)
        }
      }, 1000)
      emits('sendCode')
    }
  })
}

// 登录功能
const handleLogin = () => {
  rulesRef.value.validate(valid => {
    if (valid) {
      emits('onSubmit')
    } else {
      emits('onError')
    }
  })
}
watch(
    () => props.ruleForm,
    val => {
      rulesForm.value = val
    },
    {immediate: true}
)

</script>

<style scoped>

</style>

使用:

<template>
  <div class="login-panel">
    <div class="phone-login">
      <phone-login
          :ruleForm="ruleForm"
          :countDown="countDown"
          @sendCode="sendCode"
          @onSubmit="onSubmit"
          @onError="onError"
      >
      </phone-login>
    </div>

  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import {ElMessage} from "element-plus";

const ruleForm = reactive({
  phone: '',
  countDown: ''
})
const countDown = ref(30)

const sendCode = () => {
  // 发送验证码接口
  ElMessage({
    type: 'success',
    message: '发送验证码成功'
  })
}

const onSubmit = () => {
  alert('发送 http请求:')
  ElMessage({
    type: 'success',
    message: '保存成功'
  })
}

const onError = () => {
  ElMessage({
    type: 'warning',
    message: '校验失败'
  })
}
</script>

<style scoped lang="scss">
.login-panel {
  margin-left: 20px;
  margin-top: 20px;
}

.phone-login {
  width: 350px;
  height: 350px;
}
</style>

到此这篇关于Vue3封装登录功能的两种实现的文章就介绍到这了,更多相关Vue3 登录内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • vue3如何优雅的实现移动端登录注册模块

    前言 近期开发的移动端项目直接上了 vue3 ,新特性 composition api 确实带来了全新的开发体验.开发者在使用这些特性时可以将高耦合的状态和方法放在一起统一管理,并能视具体情况将高度复用的逻辑代码单独封装起来,这对提升整体代码架构的健壮性很有帮助. 如今新启动的每个移动端项目基本上都包含注册登录模块,本次实践过程中针对登录注册中的表单控件做了一些经验上的总结,通过抽离提取共性代码来提升代码的可维护性和开发效率. 接下来观察一下美工同学提供的图片. 注册页面 登录页面 忘记密码页面

  • Vue3项目中优雅实现微信授权登录的方法

    目录 前言 准备 实现思路 上代码 总结 前言 微信授权登录是做微信公众号开发一直绕不开的话题,而且整个授权登录流程的实现,是需要前后端配合一起完成的.在过去前后端还未分离的年代,也许我们前端并不需要太过关心授权的具体实现.然而现在都2021年了,前后端分离的架构大行其道,如何在前后端分离的情况下实现微信授权登录就成了今天要探讨的重点问题. 准备 首先,我们还是需要先梳理下微信授权整个流程是怎样的,这里我就直接将官方文档搬来: 如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制

  • Vue3封装登录功能的两种实现

    目录 方法一:使用用户名和密码进行登录 方法二:使用手机验证码登录 方法一: 使用用户名和密码进行登录 封装代码: <template> <el-form ref="ruleFormRef" status-icon :model="ruleForms" :rules="rules" label-width="120px" class="demo-ruleForm" > <el-

  • vue实现Excel文件的上传与下载功能的两种方式

    一.前言项目中使用到比较多的关于Excel的前端上传与下载,整理出来,以便后续使用或分析他人. 1.前端vue:模板下载与导入Excel 导入Excel封装了子组件,点击导入按钮可调用子组件,打开文件上传的对话框,上传成功后返回结果 <el-col style="padding: 10px 0 20px;"> <el-button class="pull-right" icon="el-icon-upload" type=&qu

  • Android编程使用WebView实现文件下载功能的两种方法

    本文实例讲述了Android编程使用WebView实现文件下载功能的两种方法.分享给大家供大家参考,具体如下: 在应用中,通常会使用到文件下载功能,一般我们都是写一个下载操作工具类,在异步任务中执行下载功能. 今天我们来看下如何使用WebView的文件下载功能! 方法1,自定义下载操作 1. 先来布局 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools=&qu

  • vue实现打印功能的两种方法

    第一种方法:通过npm 安装插件 1,安装  npm install vue-print-nb --save 2,引入  安装好以后在main.js文件中引入 import Print from 'vue-print-nb' Vue.use(Print); //注册 3,现在就可以使用了 <div id="printTest" > <p>锄禾日当午</p> <p>汗滴禾下土 </p> <p>谁知盘中餐</p&

  • vue+axios 前端实现登录拦截的两种方式(路由拦截、http拦截)

    一.路由拦截 登录拦截逻辑 第一步:路由拦截 首先在定义路由的时候就需要多添加一个自定义字段requireAuth,用于判断该路由的访问是否需要登录.如果用户已经登录,则顺利进入路由, 否则就进入登录页面. const routes = [ { path: '/', name: '/', component: Index }, { path: '/repository', name: 'repository', meta: { requireAuth: true, // 添加该字段,表示进入这个

  • JAVA实现下载文件功能的两种方法

    第一种方法: public HttpServletResponse download(String path, HttpServletResponse response) { try { // path是指欲下载的文件的路径. File file = new File(path); // 取得文件名. String filename = file.getName(); // 取得文件的后缀名. String ext = filename.substring(filename.lastIndexO

  • java获取登录者IP和登录时间的两种实现代码详解

    第一种直接用java自带的InetAddress类: import java.net.InetAddress; import java.text.SimpleDateFormat; import java.util.Date; public class test{ public static void main(String[] args) throws Exception{ InetAddress addr = InetAddress.getLocalHost(); String ip=add

  • vue用户长时间不操作退出到登录页的两种实现方式

    目录 问题描述 前端控制(方式一) 思路 代码 后端控制(方式二) 思路 代码 总结 问题描述 产品说,出于安全考虑,用户长时间不操作,就回到登录页面,让用户重新登录,就像银行的app一样.本文就记录一下实现这种效果的两种方式,分别是前端控制和后端控制,各有细节及适用使用场景 前端控制(方式一) 思路 首先,用户长时间不操作具体表现形式是啥?其实就是事件是否长时间没有被触发执行. 比如用户长时间不操作,就没有鼠标点击(click)事件.鼠标滚轮(mousewheel)事件.鼠标移动(mousem

  • vue3.0中setup的两种用法实例

    目录 前言 一.setup函数的特性以及作用 二.setup函数的注意点: 用法1:结合ref使用 用法2:代码分割 总结 前言 这篇文章主要介绍了vue3.0中setup使用,本文通过两种用法给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下 什么是setup setup是vue3新增的生命周期函数,setup的加入就是为了让vue3使用组合式API(Composition API).使用组合式API更符合大型项目的开发,通过setup可以将该部分抽离成函数,

  • javascript记住用户名和登录密码(两种方式)

    下面主要通过代码给大家展示下javascript记住用户名和登录密码,具体代码内容请看下文. 第一种方式: CONTENT     login.html     welcome.html     cookie.js     common.js login.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-t

随机推荐