vue-element-admin–让后端程序员不再抓狂

前言:作为一个后端程序员,并没有太多时间和精力去详细研究前端,毕竟前端也要吃饭呀,相煎何急,何必抢人饭碗呢。所以,前端部分的功能,能改则改,能抄则抄,囫囵吞枣,能跑就行。

先把官方的代码跑起来

  • 选择一个目录,执行git初始化命令
git init
  • 克隆代码

选择一:克隆国际化i18n分支

git clone -b i18n https://gitee.com/panjiachen/vue-element-admin.git
  • 将克隆下来的文件夹重命名:vue-element-admin修改为bhp-framework-vue,并删除.get文件夹
后端程序员福音:vue-element-admin
  • 编译器打开bhp-framework-vue,编译器根据自己喜好选择,我这里直接用IDEA
  • 执行“npm install”安装依赖
后端程序员福音:vue-element-admin
  • package.json——>右键点击Show npm Scripts展示所有命令
后端程序员福音:vue-element-admin
  • 双击dev启动前端项目,启动成功后控制台会打出访问地址,并自动用默认浏览器打开
后端程序员福音:vue-element-admin
  • 默认展示英文画面,不科学,我不喜欢,泱泱大国能用你这东西当默认语言?改它!
后端程序员福音:vue-element-admin

PS:在页面上直接切换语言可以保证自己使用,因为语言选择缓存到了浏览器。但是别的浏览器打开后仍然默认英文。因此从界面上修改解决不了根本问题。

  • 打开src\lang\index.js,修改45行的\’en\’为\’ch\’,然后重启
后端程序员福音:vue-element-admin

如下,这就可爱多了,如果你的页面还没变,先别着急掰屏幕,清除浏览器缓存重新进就行了。

后端程序员福音:vue-element-admin

选择一:克隆主线master分支

git clone  https://gitee.com/panjiachen/vue-element-admin.git其他过程参照选择一处理,处理完毕后,启动项目如下
  • 其他过程参照选择一处理,处理完毕后,启动项目如下
后端程序员福音:vue-element-admin

由于我写这个玩意大概率不会普及到全世界,所以我就不整国际化了,我选择拉取master分支,默认显示的英文,我们后边可以修改,暂时按下不表。

移除mock,连通后端

这些页面数据都是用的mock数据,不科学,我不喜欢,删它!

  • 找到vue.config.js,注释掉”before: require(\’./mock/mock-server.js\’)”,并设置代理处理跨域请求
后端程序员福音:vue-element-admin
proxy: {
      [process.env.VUE_APP_BASE_API]: {
        target: \'http://localhost:8088\',
        changeOrigin: true,
        pathRewrite: {
          [\'^\'   process.env.VUE_APP_BASE_API]: \'bhp-framework\'
        }
      }
    }
  • 修改src\api\user.js的login接口,与后台项目保持一致
后端程序员福音:vue-element-admin
export function login(data) {
  return request({
    // url: \'/vue-element-admin/user/login\',
    url: \'/auth/login\',
    method: \'post\',
    data
  })
}
  • 重启项目,测一下(前提先保证后端项目bhp-framework是启动状态,且端口为8088),点击登录按钮,报500
后端程序员福音:vue-element-admin

把手里的板砖放下,这是正常的,说明现在前后端已经通了,咱们的目的就达到了。至于报错原因嘛,那就很简单了,接口数据都没对上,肯定要报错。

完善前端登录页面

  • 打开src\views\login\index.vue,进行如下修改
<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on"
             label-position="left">
      <div class="title-container">
        <h3 class="title">北海派快速开发平台h3>
      div>
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user"/>
        span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="账户"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      el-form-item>
      <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>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="密码"
            name="password"
            tabindex="2"
            autocomplete="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>
      <el-form-item prop="code">
        <span class="svg-container">
          <svg-icon icon-class="people"/>
        span>
        <el-input
          ref="code"
          v-model="loginForm.code"
          placeholder="验证码"
          name="code"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      el-form-item>
      <div >
        <img :src="codeUrl" @click="getCode" />
        <el-button @click="getCode" type=\'text\' class="textbtn">看不清,换一张el-button>
      div>
      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;"
                 @click.native.prevent="handleLogin">登录
      el-button>
      <div style="position:relative">
        <div class="tips">
          <span>span>
          <span>span>
        div>
        <div class="tips">
          <span style="margin-right:18px;">span>
          <span>span>
        div>
        <el-button class="thirdparty-button" type="primary" @click="showDialog=true">
          关联登录
        el-button>
      div>
    el-form>
    <el-dialog title="第三方关联登录" :visible.sync="showDialog">
      别捉急,开发中……
      <br>
      <br>
      <br>
      <social-sign/>
    el-dialog>
  div>
template>
<script>
  // import { validUsername } from \'@/utils/validate\'
  import {getCodeImg} from \'../../api/login\'
  import SocialSign from \'./components/SocialSignin\'
  export default {
    name: \'Login\',
    components: { SocialSign },
    data() {
      const validateUsername = (rule, value, callback) => {
        if (value.length < 1) {
          callback(new Error(\'请输入帐户\'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (value.length < 1) {
          callback(new Error(\'请输入密码\'))
        } else {
          callback()
        }
      }
      const validateCode = (rule, value, callback) => {
        if (value.length < 1) {
          callback(new Error(\'请输入验证码\'))
        } else {
          callback()
        }
      }
      return {
        codeUrl: "",
        loginForm: {
          username: \'\',
          password: \'\',
          code: \'\',
          uuid: \'\'
        },
        loginRules: {
          username: [{ required: true, trigger: \'blur\', validator: validateUsername }],
          password: [{ required: true, trigger: \'blur\', validator: validatePassword }],
          code: [{ required: true, trigger: \'blur\', validator: validateCode }]
        },
        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)
      this.getCode();
    },
    mounted() {
      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(e) {
        const { key } = e
        this.capsTooltip = key && key.length === 1 && (key >= \'A\' && key <= \'Z\')
      },
      showPwd() {
        if (this.passwordType === \'password\') {
          this.passwordType = \'\'
        } else {
          this.passwordType = \'password\'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      getCode() {
        getCodeImg().then(res => {
          console.log(res);
          this.codeUrl = "data:image/gif;base64,"   res.data.img;
          this.loginForm.uuid = res.data.uuid;
        });
      },
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.$store.dispatch(\'user/login\', this.loginForm)
              .then(() => {
                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>
<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
  $bg: #283443;
  $light_gray: #fff;
  $cursor: #fff;
  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }
  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;
      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;
        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }
    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
style>
<style lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #eee;
  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;
    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }
    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;
      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }
    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }
    .title-container {
      position: relative;
      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }
    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }
    @media only screen and (max-width: 470px) {
      .thirdparty-button {
        display: none;
      }
    }
  }
style>
  • 将src\api\user.js重命名为login.js,并新增一个获取验证码的请求
import request from \'@/utils/request\'
export function login(data) {
  return request({
    // url: \'/vue-element-admin/user/login\',
    url: \'/auth/login\',
    method: \'post\',
    data
  })
}
export function getInfo(token) {
  return request({
    url: \'/vue-element-admin/user/info\',
    method: \'get\',
    params: { token }
  })
}
export function logout() {
  return request({
    url: \'/vue-element-admin/user/logout\',
    method: \'post\'
  })
}
// 获取验证码
export function getCodeImg() {
  return request({
    url: \'/captcha\',
    method: \'get\'
  })
}
  • 将src\utils\request.js中的正确响应码从20000修改为200(跟后端保持一致)
后端程序员福音:vue-element-admin
  • 重启后,最终展示效果如下
后端程序员福音:vue-element-admin

补充:重写了验证码生成方法

根据登录页面效果图不难发现,验证码由原来的扭曲文字变为了数学公式。

这是因为之前用扭曲文字作为验证码时,人眼识别验证码也很困难,所以重新处理了验证码的生成方法。

  • CaptchaCtl.java
package top.baohaipeng.framework.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.math.Calculator;
import cn.hutool.core.util.IdUtil;
import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.baohaipeng.framework.common.CommonData;
import top.baohaipeng.framework.common.R;

/**
 * @ClassName CaptchaCtl
 * @Description 验证码
 * @Author 头条号:北海派bhp
 * @Date 2020/9/25 21:42
 * @Version 1.0
 **/
@RestController
@RequestMapping("bhp-framework")
public class CaptchaCtl {

    @Autowired
    Cache<String, Object> captchaCache;

    @GetMapping("captcha")
    public R getCaptcha() {

        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(111, 36);
        String uuid = IdUtil.simpleUUID();

        // 自定义验证码内容为四则运算方式
        captcha.setGenerator(new MathGenerator());
        // 重新生成code
        captcha.createCode();
        // 验证码对应的字符串
        String code = String.valueOf((int)Calculator.conversion(captcha.getCode()));
        System.out.println("真实验证码是:"   code);

        // 放入缓存
        captchaCache.put(uuid, code);
        System.out.println("uuid: "   uuid);

        // 返回响应对象
        CommonData data = new CommonData();
        data.setUuid(uuid);
        data.setImg(captcha.getImageBase64());

        return R.success(data);
    }

    @GetMapping("check/{uuid}/{code}")
    public R getCache(@PathVariable String uuid, @PathVariable String code) {

        // 从缓存中取,找不到返回null
        String s = (String) captchaCache.asMap().getOrDefault(uuid, null);

        if (s == null) {
            return R.error("验证码已过期");
        } else if (code.equals(s)) {
            return R.success("验证通过");
        }
        return R.error();
    }

}

至此,项目基本引入了后端程序员福音——vue-element-admin的页面,下面会逐步处理完善。

内容出处:,

声明:本网站所收集的部分公开资料来源于互联网,转载的目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。如果您发现网站上有侵犯您的知识产权的作品,请与我们取得联系,我们会及时修改或删除。文章链接:http://www.yixao.com/share/12562.html

发表评论

登录后才能评论