时间:2022-06-07 09:21:00 | 栏目:vue | 点击:次
首先修改统一请求路径为我们自己的登陆接口,在.env.development文件中
# base api VUE_APP_BASE_API = 'http://localhost:8081/api/dsxs/company'
打开登陆页面,src/views/login/index.vue
<template> <div class="login-container"> <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> <el-form-item prop="username"> <span class="svg-container"> <svg-icon icon-class="user" /> </span> <el-input ref="username" v-model="loginForm.username" placeholder="Username" name="username" type="text" tabindex="1" auto-complete="on" /> </el-form-item> <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="Password" name="password" tabindex="2" auto-complete="on" @keyup.enter.native="handleLogin" /> <span class="show-pwd" @click="showPwd"> <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" /> </span> </el-form-item> <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">Login</el-button> <div class="tips"> <span style="margin-right:20px;">username: admin</span> <span> password: any</span> </div> </el-form> </div> </template>
可以看到页面使用组件对loginForm进行名称和密码的绑定
data() { 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() } }
这段代码则为对输入的内容进行验证
看登陆的方法
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 || '/' }) this.loading = false }).catch(() => { this.loading = false }) } else { return false } }) }
其中 this.$store.dispatch('user/login', this.loginForm),不是请求后台user/login接口,而是转到modules下的user.js中的login方法,打开store/modules/user.js可以看到login方法。而login方法则是调用api/user.js中的login方法。
此时修改store/modules/user.js接收后台传来的响应数据
const actions = { // user login login({ commit }, userInfo) { const { username, password } = userInfo return new Promise((resolve, reject) => { login({ username: username.trim(), password: password }).then(response => { console.log(response) const { data } = response commit('SET_TOKEN', response.data.token) setToken(response.data.token) resolve() }).catch(error => { reject(error) }) }) },
同时在api/user.js中修改为我们后台的请求地址
import request from '@/utils/request' export function login(data) { return request({ url: 'userlogin', method: 'post', data }) } export function getInfo(token) { return request({ url: 'userinfo', method: 'get', params: { token } }) }
此时可以发现模板采用的登陆方式是请求两次,第一次通过用户名密码请求后端,后端判断后,返回对应的token。然后在通过getInfo方法请求后端,获取用户真实信息。
在编写后端之前还需要修改utils/request.js,因为默认状态码是20000为成功,而我们平时返回的是200
// if the custom code is not 20000, it is judged as an error. if (res.code !== 200) { Message({ message: res.message || 'Error', type: 'error', duration: 5 * 1000 })
简单的编写后端代码,登陆方法根据账号密码查出用户信息,根据用户id与name生成token并返回,userinfo则是对token进行获取,在查出对应值进行返回。
@CrossOrigin @RestController @RequestMapping("/api/dsxs/company") public class CompanyuserController { @Autowired private CompanyuserService companyuserService; //后台登陆 @PostMapping("userlogin") @ResponseBody public R userlogin(@RequestBody UserVo userVo){ Companyuser companyuser = companyuserService.login(userVo); String token = JwtHelper.createToken(companyuser.getId(), companyuser.getName()); return R.ok().data("token",token); } //返回信息 @GetMapping("userinfo") public R userinfo( String token){ Integer userId = JwtHelper.getUserId(token); System.out.println("===="); Companyuser user = companyuserService.getById(userId); HashMap<String, String> map = new HashMap<>(); map.put("name",user.getName()); map.put("avatar",user.getAvatar()); return R.ok().data("name",user.getName()).data("avatar",user.getAvatar()); } }
我这里使用@CrossOrigin注解解决的跨域问题。