【Vue框架】基本的login登录

前言

最近事情比较多,只能抽时间看了,放几天就把之前弄的都忘了,现在只挑着核心的部分看。现在铺垫了这么久,终于可以看前端最基本的登录了😂。

1、views\login\index.vue

由于代码比较长,这里将vue和js代码分开展示。

1.1、login的vue代码

<template>
  <div class="login-container">
    <!-- 使用`loginForm`作为表单的数据模型,
    `loginRules`作为表单字段的验证规则,
    `ref`属性为`loginForm`用于在代码中引用该表单组件,
    `class`属性添加了`login-form`样式类名,
    `auto-complete`设置为`on`表示浏览器会自动完成输入,
    `label-position`设置为`left`表示标签位于输入框左侧-->
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
      <!--标题-->
      <div class="title-container">
        <h3 class="title">Login Form</h3>
      </div>
      <!--一个表单项组件,用于包裹一个字段。`prop`属性设置为"username",用于表单验证。-->
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <!--一个Element UI的输入框组件
          `ref="username"`:给输入框组件添加一个引用,用于在代码中引用该输入框组件
          `v-model="loginForm.username"`:利用双向绑定,将输入框的值与`loginForm`对象中的`username`属性进行绑定
          `placeholder="输入框的占位文字Username"`:设置输入框的占位文字"
          `type="text"`:设置输入框的类型为文本输入
          `tabindex="1"`:设置输入框的tab索引为1,用于设置键盘焦点的顺序
          `auto-complete="on"`:设置浏览器自动完成输入-->
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="输入框的占位文字Username"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>
      <!--一个Element UI的工具提示组件,用于显示大写锁定键(Caps lock)的状态提示信息-->
      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <!--`@keyup.native="checkCapslock"`:当键盘按键弹起时触发`checkCapslock`方法,用于检查大写锁定键的状态
           `@blur="capsTooltip = false"`:当输入框失去焦点时,隐藏大写锁定键提示
           `@keyup.enter.native="handleLogin"`:当按下Enter键时触发`handleLogin`方法,完成登录操作-->
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="输入框的占位文字Password"
            name="password"
            tabindex="2"
            auto-complete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>
      <!--`@click`是Vue的事件绑定语法,
      `.native`修饰符用于监听组件根元素的原生(非自定义)事件。
      `.prevent`修饰符用于阻止事件的默认行为,例如阻止表单的提交行为-->
      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">Login</el-button>

      <div style="position:relative">
        <div class="tips">
          <span>Username : admin</span>
          <span>Password : any</span>
        </div>
        <div class="tips">
          <span style="margin-right:18px;">Username : editor</span>
          <span>Password : any</span>
        </div>

        <el-button class="thirdparty-button" type="primary" @click="showDialog=true">
          Or connect with
        </el-button>
      </div>
    </el-form>

    <el-dialog title="Or connect with" :visible.sync="showDialog">
      Can not be simulated on local, so please combine you own business simulation! ! !
      <br>
      <br>
      <br>
      <social-sign />
    </el-dialog>
  </div>
</template>

1.2、login的js代码

<script>
import { validUsername } from '@/utils/validate'
import SocialSign from './components/SocialSignin'

export default {
  name: 'Login',
  // 这个引入`SocialSign`中export default中所有的东西;SocialSign是第三方登录的内容
  components: { SocialSign },
  data() {
    // callback:函数变量,传入函数名称,可以复用,动态传入不同的函数使用
    // 定义验证方式
    const validateUsername = (rule, value, callback) => {
      // 验证用户名是否符合规则
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    // 一般变量的定义,都是在data()下的return中写
    return {
      // 用来记录前端交互的用户名和密码
      loginForm: {
        username: 'admin',
        password: '111111'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  // `mounted()`,在组件挂载后被调用
  mounted() {
    // `this.$refs`来访问已经挂载的`username`输入框组件,并调用其`focus()`方法来设置该输入框组件获取焦点
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    // 检查大写锁定键的方法
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (shiftKey && (key >= 'a' && key <= 'z') || !shiftKey && (key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    // 是否显示具体密码
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 实际登录的方法
    handleLogin() {
      // `validate`是`this.$refs.loginForm`访问到的登录表单组件的方法,
      // 这个方法会根据组件的表单验证规则进行验证,并将验证结果以参数的形式传递给回调函数
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 访问store/modules/user.js中action下的方法login
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              // `this.$router`全局路由,通过`push({path:'路径',query:{id:参数}})`进行路由跳转
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
}
</script>

上面的内容涉及到callbackthis.$router的内容,具体可以参考以下链接了解:

  1. callback的使用
  2. vue this.$router.push 实现路由跳转

2、前端登录的执行流程图

根据views\login\index.vue的代码和【Vue框架】用户和请求的内容,整理得到他们的执行流程图,如下:
在这里插入图片描述
PS:前后端response内容关系不清楚的,可以看【Vue框架】用户和请求中的第5节。

3、src\permission.js

3.1 代码

import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar 用于显示进度条,NProgress显示页面加载或异步操作进度的JavaScript库
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title' // 用于获取页面标题

// showSpinner: false不会显示旋转的加载图标,只会显示进度的条形动画
NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 定义了一些不需要进行路由重定向的白名单路径,例如`/login`和`/auth-redirect`。这些路径将被认为是无需进行重定向或权限检查的安全路径
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

/**
 * 在 Vue Router 中,全局前置守卫(Global before Guards)是一种用于拦截导航的机制,
 * 允许在路由切换之前对导航进行一些操作,比如进行身份验证、权限检查等。
 * 全局前置守卫是在 Vue Router 实例中注册的一组函数(constantRoutes和asyncRoutes),会在每次导航发生之前按照顺序执行。
 * 过调用 `router.beforeEach` 方法来注册全局前置守卫
 * 1. `to`:即将进入的路由。
 * 2. `from`:当前导航正要离开的路由。
 * 3. `next`:一个函数,用于控制导航的行为。需要在回调函数最后调用 `next` 方法来确认导航是否继续。
 */
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page 如果用户已经登录并且正在访问登录页面
      // 【用户从新打开页面,应该默认访问首页,然后这里来判断用户是否登录,如果登录就可以直接访问首页】
      // 重定向到主页
      next({ path: '/' })
      // 结束进度条
      NProgress.done()
    } else {
      // 如果用户已经登录,但不是在访问登录页面
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        // 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          // store是Vuex的实例,dispatch访问到里面action定义的方法('user/getInfo')
          const { roles } = await store.dispatch('user/getInfo')

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          // dynamically add accessible routes
          // `addRoutes`方法只能在实例化Vue Router之后才能调用,且只能调用一次。否则会导致路由异常
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`) // 重定向到登录页面,并附带返回地址
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

3.2 什么是路由守卫(导航守卫)

  • 个人理解:
    作用:从一个Vue文件(路由)跳转到另一个Vue文件(另一个路由),就会通过路由守卫来判断是否有权限正常跳转。

在这里插入图片描述
补充:
this.$router全局路由,通过push({path:'路径',query:{id:参数}})进行路由跳转,如下代码:

 this.$router.push({ path: this.redirect || '/', query: this.otherQuery })

个人理解:
push这里应该像是把route(路由)进栈,然后再根据路由守卫的next()指向要跳转的路由。

在这里插入图片描述
PS:理解能力有限,我画的这个是非常浅显的理解,如果大佬们想深入理解可以看下官方文档Vue Router
在这里插入图片描述

  • route是什么?
    在这里插入图片描述

3.3 代码中的主要逻辑

在3.2中提到,路由守卫是用来判断是否有权限正常跳转的,admin代码给出的判断逻辑如下图:
在这里插入图片描述
PS:一般好像也就是这样的逻辑

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/89149.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

有哪些前端调试和测试工具? - 易智编译EaseEditing

前端开发调试和测试工具帮助开发人员在开发过程中发现和修复问题&#xff0c;确保网站或应用的稳定性和性能。以下是一些常用的前端调试和测试工具&#xff1a; 调试工具&#xff1a; 浏览器开发者工具&#xff1a; 现代浏览器&#xff08;如Chrome、Firefox、Safari等&#…

剪枝基础与实战(2): L1和L2正则化及BatchNormalization讲解

1. CIFAR10 数据集 CIFAR10 是深度学习入门最先接触到的数据集之一,主要用于图像分类任务中,该数据集总共有10个类别。 图片数量:6w 张图片宽高:32x32图片类别:10Trainset: 5w 张,5 个训练块Testset: 1w 张,1 个测试块Pytorch 集成了很多常见数据集的API, 可以通过py…

STM32 无法烧录

1. 一直显示芯片没连接上&#xff0c;检查连线也没问题&#xff0c;换了个ST-Link 烧录器还是连不上&#xff0c;然后又拿这个烧录器去其它板子上试下&#xff0c;就可以连接上&#xff0c;说明我连线没问题&#xff0c;烧录器也没问题&#xff0c;驱动什么的更是没问题&#x…

慕课网 Go工程师 第三周 package和gomodules章节

Go包的引入&#xff1a; 包名前面加匿名&#xff0c;只引入但不使用&#xff0c;如果对应包有init函数&#xff0c;会执行init函数&#xff08;初始化操作&#xff09; 包名前面加. 把这个包的结构体和方法导入当前包&#xff0c;慎用&#xff0c;你不知道当前包和被引入的包用…

WPF实战项目十二(API篇):配置AutoMapper

1、新建类库WPFProjectShared&#xff0c;在类库下新建文件夹Dtos&#xff0c;新建BaseDto.cs&#xff0c;继承INotifyPropertyChanged&#xff0c;实现通知更新。 public class BaseDto : INotifyPropertyChanged{public int Id { get; set; }public event PropertyChangedEv…

七大出海赛道解读,亚马逊云科技为行业客户量身打造解决方案

伴随全球化带来的新机遇和国内市场的进一步趋于饱和&#xff0c;近几年&#xff0c;中国企业出海快速升温&#xff0c;成为了新的创业风口和企业的第二增长曲线。从范围上看&#xff0c;出海市场由近及远&#xff0c;逐步扩张。从传统的东南亚市场&#xff0c;到成熟的北美、欧…

Linux 网络编程 和 字节序的概念

网络编程概述 不同于之前学习的所有通讯方法&#xff0c;多基于Linux内核实现&#xff0c;只能在同一个系统中不同进程或线程间通讯&#xff0c;Linux的网络编程可以实现真正的多机通讯&#xff01; 两个不相关的终端要实现通讯&#xff0c;必须依赖网络&#xff0c;通过地址…

Element table根据字段合并表格(可多字段合并),附带拖拽列动态合并

效果如图&#xff0c;姓名 数值1 字段进行自动合并 封装合并列js - tableMerge.js // 获取列合并的行数 // params // tableData: 表格数据 // mergeId: 合并的列的字段名 export const tagRowSpan (tableData, mergeId) >{const tagArr [];let pos 0;tableData.map((i…

网络安全入口设计模式

网络安全入口涵盖了几种设计模式&#xff0c;包括全局路由模式、全局卸载模式和健康终端监控模式。网络安全入口侧重于&#xff1a;全局路由、低延迟故障切换和在边缘处减轻攻击。 上图包含了3个需求。 •网络安全入口模式封装了全局路由模式。因此&#xff0c;实现可以将请求路…

openCV实战-系列教程5:边缘检测(Canny边缘检测/高斯滤波器/Sobel算子/非极大值抑制/线性插值法/梯度方向/双阈值检测 )、原理解析、源码解读

打印一个图片可以做出一个函数&#xff1a; def cv_show(img,name):cv2.imshow(name,img)cv2.waitKey()cv2.destroyAllWindows() 1、Canny边缘检测流程 Canny是一个科学家在1986年写了一篇论文&#xff0c;所以用自己的名字来命名这个检测算法&#xff0c;Canny边缘检测算法…

【数据库】使用ShardingSphere+Mybatis-Plus实现读写分离

书接上回&#xff1a;数据库调优方案中数据库主从复制&#xff0c;如何实现读写分离 ShardingSphere 实现读写分离的方式是通过配置数据源的方式&#xff0c;使得应用程序可以在执行读操作和写操作时分别访问不同的数据库实例。这样可以将读取操作分发到多个从库&#xff08;从…

【⑭MySQL | 数据类型(二)】字符串 | 二进制类型

前言 ✨欢迎来到小K的MySQL专栏&#xff0c;本节将为大家带来MySQL字符串 | 二进制类型类型的分享✨ 目录 前言5 字符串类型6 二进制类型总结 5 字符串类型 字符串类型用来存储字符串数据&#xff0c;还可以存储图片和声音的二进制数据。字符串可以区分或者不区分大小写的串比…

【数据仓库】Linux、CentOS源码安装Superset

Linux、CentOS源码安装Superset步骤&#xff0c;遇到的各种问题。 报错问题&#xff1a; Linux下pip版本问题 You are using pip version 8.1.2, however version 22.2.2 is available. 解决办法&#xff1a; 安装python3的pip yum install python3-pip再升级 pip3 install…

Qt跨平台无边框窗口探索记录

一、前言 实现的效果为&#xff1a;通过黑色矩形框预操作&#xff0c;鼠标释放时更新窗口。效果图如下&#xff1a; 1.功能 1.1 已实现功能 8个方向的缩放标题栏拖动标题栏双击最大化/正常窗口窗口最小尺寸预操作框颜色与背景色互补多屏幕默认标题栏 1.2 待开发功能 拖动到…

Python自带单元测试框架UnitTest,如何生成独立的测试报告?

前言 当我们在公司跑UI自动化的时候&#xff0c;一般都会选择晚上或者工作日休息时进行运行。那么当程序这时运行&#xff0c;如果自动化出现错误&#xff0c;我们又不知道当时页面是什么原因导致测试用例失败&#xff0c;怎么办&#xff1f; 这个时候我们就想到在其测试用例…

搭建CFimagehost私人图床,实现公网远程访问的详细指南

文章目录 1.前言2. CFImagehost网站搭建2.1 CFImagehost下载和安装2.2 CFImagehost网页测试2.3 cpolar的安装和注册 3.本地网页发布3.1 Cpolar临时数据隧道3.2 Cpolar稳定隧道&#xff08;云端设置&#xff09;3.3.Cpolar稳定隧道&#xff08;本地设置&#xff09; 4.公网访问测…

java八股文面试[数据结构]——ConcurrentHashMap原理

HashMap不是线程安全&#xff1a; 在并发环境下&#xff0c;可能会形成环状链表&#xff08;扩容时可能造成&#xff0c;具体原因自行百度google或查看源码分析&#xff09;&#xff0c;导致get操作时&#xff0c;cpu空转&#xff0c;所以&#xff0c;在并发环境中使用HashMap是…

Go 1.21中值得关注的几个变化

美国时间2023年8月8日&#xff0c;Go团队在Go官博上正式发布了1.21版本[2]&#xff01; 早在今年4月末&#xff0c;我就撰写了文章《Go 1.21新特性前瞻[3]》&#xff0c;对Go 1.21可能引入的新特性、新优化和新标准库包做了粗略梳理。 在6月初举办的GopherChina 2023大会上[4]&…

[Docker] Windows 下基于WSL2 安装

Docker 必须部署在 Linux 内核的系统上。如果其他系统想部署 Docker 就必须安装一个虚拟 Linux 环境。 1. 开启虚拟化 进入系统BIOS&#xff08;AMD 为 SVM&#xff1b;Intel 为 Intel-vt&#xff09;改为启用(enable) 2. 开启WSL 系统设置->应用->程序和功能->…

微信小程序,封装身高体重选择器组件

wxml代码&#xff1a; // 微信小程序的插值语法不支持直接使用Math <wxs src"./ruler.wxs" module"math"></wxs> <view class"ruler-container"><scroll-view scroll-left"{{scrollLeft}}" enhanced"{{tru…