电商后台管理系统整体采用前后端分离的开发模式,其中前端项目是基于 Vue 技术栈的 SPA(单页应用程序) 项目
详见【Vue】vue-cli - 图形化创建项目 - 配置项目 - axios - elementUI - 码云SSH公钥设置 - Gitee同步
cd E:\YKcode\web\myProject01\api\vue_api_server
cnpm install
出错了就多 npm install
或 cnpm install
几下
node app.js
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210314154316727.png?x-oss-process=image/waterma
① 在登录页面输入用户名和密码
② 调用后台接口进行验证
③ 通过验证之后,根据后台的响应状态跳转到项目主页
相关参考【彻底理解cookie,session,token - 墨颜丶 - 博客园】
创建分支
git checkout -b login
查看分支
git branch
import Login from '../components/Login.vue'
const routes = [
{
path: '/', redirect: '/login' },
{
path: '/login', component: Login }
]
<div id="app">
<router-view>router-view>
div>
/* 全局样式表 */
html,
body,
#app {
height: 100%;
margin: 0;
padding: 0;
min-width: 1366px;
}
// 导入全局样式表
import './assets/css/global.css'
<div class="login_container">
<div class="login_box">div>
div>
.login_container {
background-color: #409eff;
height: 100%;
}
.login_box {
width: 450px;
height: 300px;
background-color: #fff;
border-radius: 3px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="avatar_box">
<img src="../assets/YK.jpg" alt="" />
div>
.avatar_box {
height: 130px;
width: 130px;
border: 1px solid #eee;
border-radius: 50%;
padding: 10px;
box-shadow: 0 0 10px #ddd;
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
}
img {
width: 100%;
height: 100%;
border-radius: 50%;
background-color: #eee;
}
import Vue from 'vue'
import {
Button, Form, FormItem, Input } from 'element-ui'
Vue.use(Button)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)
<el-form label-width="0px" class="login_form">
<el-form-item>
<el-input>el-input>
el-form-item>
<el-form-item>
<el-input>el-input>
el-form-item>
<el-form-item>
<el-button type="primary" class="btns">登录el-button>
<el-button type="info">重置el-button>
el-form-item>
el-form>
.login_form {
position: absolute;
bottom: 0;
width: 100%;
padding: 0 20px;
box-sizing: border-box;
}
.btns {
display: flex;
justify-content: flex-end;
}
https://element.eleme.cn/#/zh-CN/component/input
官方图标库 https://element.eleme.cn/#/zh-CN/component/icon
<el-input prefix-icon="el-icon-user">el-input>
<el-input prefix-icon="el-icon-lock">el-input>
import './assets/fonts/iconfont.css'
<el-form :model="loginForm">
<el-input v-model="loginForm.username">el-input>
<el-input v-model="loginForm.password" type="password">el-input>
el-form>
export default {
data () {
return {
// 这是登录表单的数据绑定对象
loginForm: {
username: 'admin',
password: '123456'
}
}
}
}
<el-form :rules="loginFormRules">
<el-form-item prop="username">
<el-input v-model="loginForm.username">el-input>
el-form-item>
<el-form-item prop="password">
<el-input v-model="loginForm.password" type="password">el-input>
el-form-item>
el-form>
export default {
data () {
return {
loginFormRules: {
// 验证用户名是否合法
username: [
{
required: true, message: '请输入登录名称', trigger: 'blur' },
{
min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
// 验证密码是否合法
password: [
{
required: true, message: '请输入登录密码', trigger: 'blur' },
{
min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
]
}
}
}
}
<el-form ref="loginFormRef">el-form>
<el-button type="info" @click="resetLoginForm">重置el-button>
methods: {
// 点击重置按钮,重置登录表单
resetLoginForm () {
// console.log(this) // VueComponent
this.$refs.loginFormRef.resetFields()
}
}
<el-button type="primary" @click="login">登录el-button>
import axios from 'axios'
// 配置请求的根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
Vue.prototype.$http = axios
import {
Message } from 'element-ui'
Vue.prototype.$message = Message // 弹框提示组件挂在在Vue原型上
methods: {
login () {
this.$refs.loginFormRef.validate(async (valid) => {
// console.log(valid) // false/ture
if (!valid) return
const {
data: result } = await this.$http.post('login', this.loginForm)
// console.log(result) //Promise
if (result.meta.status !== 200) return this.$message.error('登录失败')
this.$message.success('登录成功')
// 1. 将登录成功之后的 token 保存到客户端的 sessionStorage 中(会话期间的存储机制)(所以不放在loaclStorage中)
window.sessionStorage.setItem('token', result.data.token)
// 2. 通过编程式导航跳转到后台主页,路由地址是 /home
this.$router.push('/home')
})
}
}
import Home from '../components/Home.vue'
const routes = [
{
path: '/home', component: Home, }
]
如果用户没有登录,但是直接通过URL访问特定页面,需要重新导航到登录页面
router/index.js
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
// to 将要访问的路径
// from 代表从哪个路径跳转而来
// next 是一个函数, 表示放行 ①next()放行 ②next('/login')强制跳转
if (to.path === '/login') return next() // 访问登录页,直接放行
// 获取token
const tokenStr = window.sessionStorage.getItem('token')
if (!tokenStr) return next('/login') // 没有token 强制跳转
next() // 否则(有token)直接放行
})
基于token的方式实现退出比较简单,只需要销毁本地的token即可。
这样,后续的请求就不会携带token,必须重新登录生成一个新的token之后才可以访问页面
<el-button type="info" @click="logout">退出el-button>
methods: {
logout() {
window.sessionStorage.clear()
this.$router.push('/login')
}
}
<template>
<div class="login_container">
<div class="login_box">
<div class="avatar_box">
<img src="../assets/YK.jpg" alt="" />
div>
<el-form
ref="loginFormRef"
:model="loginForm"
:rules="loginFormRules"
label-width="0px"
class="login_form"
>
<el-form-item prop="username">
<el-input
prefix-icon="el-icon-user"
v-model="loginForm.username"
>el-input>
el-form-item>
<el-form-item prop="password">
<el-input
prefix-icon="el-icon-lock"
v-model="loginForm.password"
type="password"
>el-input>
el-form-item>
<el-form-item class="btns">
<el-button type="primary" @click="login">登录el-button>
<el-button type="info" @click="resetLoginForm">重置el-button>
el-form-item>
el-form>
div>
div>
template>
<script>
export default {
data () {
return {
// 这是登录表单的数据绑定对象
loginForm: {
username: 'admin',
password: '123456'
},
// 这是表单验证规则对象
loginFormRules: {
// 验证用户名是否合法
username: [
{
required: true, message: '请输入登录名称', trigger: 'blur' },
{
min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
// 验证密码是否合法
password: [
{
required: true, message: '请输入登录密码', trigger: 'blur' },
{
min: 6,
max: 15,
message: '长度在 6 到 15 个字符',
trigger: 'blur'
}
]
}
}
},
methods: {
// 点击重置按钮,重置登录表单
resetLoginForm () {
// console.log(this) // VueComponent
this.$refs.loginFormRef.resetFields()
},
login () {
this.$refs.loginFormRef.validate(async (valid) => {
// console.log(valid) // false/ture
if (!valid) return
const {
data: result } = await this.$http.post('login', this.loginForm)
// console.log(result)
if (result.meta.status !== 200) return this.$message.error('登录失败')
this.$message.success('登录成功')
// 将登录成功之后的token 保存到客户端的 sessionStorage 中(会话期间的存储机制)(所以不放在loaclStorage中)
console.log(result)
window.sessionStorage.setItem('token', result.data.token)
// 通过编程式导航跳转到后台主页,路由地址是 /home
this.$router.push('/home')
})
}
}
}
script>
<style scoped>
.login_container {
background-color: #409eff;
height: 100%;
}
.login_box {
width: 450px;
height: 300px;
background-color: #fff;
border-radius: 3px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.avatar_box {
height: 130px;
width: 130px;
border: 1px solid #eee;
border-radius: 50%;
padding: 10px;
box-shadow: 0 0 10px #ddd;
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
}
img {
width: 100%;
height: 100%;
border-radius: 50%;
background-color: #eee;
}
.login_form {
position: absolute;
bottom: 0;
width: 100%;
padding: 0 20px;
box-sizing: border-box;
}
.btns {
display: flex;
justify-content: flex-end;
}
style>
git status
git add .
git commit -m "完成了登录功能"
git branch
git checkout master
git merge login
git push
https://gitee.com/ykang2020/vue_shop
git checkout login
git push -u origin login
<el-container class="home_container">
<el-header>Headerel-header>
<el-container>
<el-aside width="200px">Asideel-aside>
<el-main>Mainel-main>
el-container>
el-container>
.home_container {
height: 100%;
}
.el-header {
background-color: #373d41;
}
.el-aside {
background-color: #333744;
}
.el-main {
background-color: #eaedf1;
}
<el-header>
<div>
<img src="../assets/heima.png" alt="" />
<span>电商后台管理系统span>
div>
<el-button type="info" @click="logout">退出el-button>
el-header>
.el-header {
background-color: #373d41;
display: flex;
justify-content: space-between;
padding-left: 0;
align-items: center;
color: #fff;
font-size: 20px;
}
.el-header > div {
display: flex;
align-items: center;
}
.el-header > div > span {
margin-left: 15px;
}
菜单分为二级,并且可以折叠
<el-menu>
<el-submenu>
<i class="el-icon-menu">i>
<span>一级菜单span>
<el-menu-item>
<i class="el-icon-menu">i>
<span slot="title">二级菜单span>
el-menu-item>
el-submenu>
el-menu>
需要授权的 API ,必须在请求头中使用 Authorization字段提供 token 令牌
后台除了登录接口之外,都需要token权限验证,我们可以通过添加axios请求拦截器来添加token,以保证拥有获取数据的权限
在main.js中添加代码,在将axios挂载到vue原型之前添加下面的代码
// 通过axios请求拦截器添加token,保证拥有获取数据的权限
axios.interceptors.request.use(config => {
// 为请求头对象,添加 Token 验证的 Authorization 字段
// console.log(config)
config.headers.Authorization = window.sessionStorage.getItem('token')
// 在最后必须 return config
return config
})
Home.vue
页面加载之前就要获取数据,定义生命周期函数
data() {
return {
// 左侧菜单数据
menulist: []
}
},
created() {
this.getMenuList()
this.activePath = window.sessionStorage.getItem('activePath')
},
methods: {
// 获取所有的菜单
async getMenuList() {
const {
data: result } = await this.$http.get('menus')
if (result.meta.status !== 200) return this.$message.error(result.meta.msg)
this.menulist = result.data
console.log(result)
}
}
<el-submenu :index="item.id+''" v-for="item in menulist" :key="item.id">
<template slot="title">
<span>{
{item.authName}}span>
template>
<el-menu-item :index="subItem.id+''" v-for="subItem in item.children" :key="subItem.id">
<i class="el-icon-menu">i>
<span>{
{subItem.authName}}span>
el-menu-item>
el-submenu>
通过更改el-menu的active-text-color属性可以设置侧边栏菜单中点击的激活项的文字颜色
<el-menu background-color="#333744" text-color="#fff" active-text-color="rgb(64,158,255)">
通过更改菜单项模板(template)中的i标签的类名,可以将左侧菜单栏的图标进行设置
在数据中添加一个iconsObj,然后将图标类名进行数据绑定
iconsObj: {
125: 'el-icon-s-custom',
103: 'el-icon-s-check',
101: 'el-icon-s-goods',
102: 'el-icon-s-order',
145: 'el-icon-s-marketing'
}
一级菜单图标绑定iconsObj中的数据:
<!-- 图标 -->
<i :class="iconsObj[item.id]"></i>
为了保持左侧菜单每次只能打开一个,显示其中的子菜单,我们可以在el-menu中添加一个属性unique-opened
或者也可以数据绑定进行设置(此时true认为是一个bool值,而不是字符串) :unique-opened=“true”
<el-menu unique-opened>
解决边框问题
.el-menu {
border-right: none;
}
<el-aside :width="isCollapse ? '64px':'200px'">
<div class="toggle-button" @click="toggleCollapse">|||div>
<el-menu :collapse="isCollapse" :collapse-transition="false">
.toggle-button {
background-color: #4A5064;
font-size: 10px;
line-height: 24px;
color: rgb(144,147,153);
text-align: center;
letter-spacing: 0.2em;
cursor: pointer
}
// 点击按钮切换菜单折叠与展开
toggleCollapse() {
this.isCollapse = !this.isCollapse
}
import Welcome from '../components/Welcome.vue'
const routes = [
{
path: '/home',
component: Home,
redirect: '/welcome',
children: [{
path: '/welcome', component: Welcome }]
}
]
<el-main>
<router-view>router-view>
el-main>
<el-menu router>
<el-menu-item :index="'/'+subItem.path" v-for="subItem in item.children" :key="subItem.id">
<template>
<el-container class="home_container">
<el-header>
<div>
<img src="../assets/heima.png" alt="" />
<span>电商后台管理系统span>
div>
<el-button type="info" @click="logout">退出el-button>
el-header>
<el-container>
<el-aside :width="isCollapse ? '64px':'200px'">
<div class="toggle-button" @click="toggleCollapse">|||div>
<el-menu
background-color="#333744"
text-color="#fff"
active-text-color="rgb(64,158,255)"
unique-opened
:collapse="isCollapse"
:collapse-transition="false"
router
:default-active="activePath"
>
<el-submenu :index="item.id+''" v-for="item in menulist" :key="item.id">
<template slot="title">
<i :class="iconsObj[item.id]">i>
<span>{
{item.authName}}span>
template>
<el-menu-item :index="'/'+subItem.path" v-for="subItem in item.children" :key="subItem.id" @click="saveNavState('/'+subItem.path)">
<i class="el-icon-menu">i>
<span>{
{subItem.authName}}span>
el-menu-item>
el-submenu>
el-menu>
el-aside>
<el-main>
<router-view>router-view>
el-main>
el-container>
el-container>
template>
<script>
export default {
data() {
return {
// 左侧菜单数据
menulist: [],
// 定义一个字体图标对象
iconsObj: {
125: 'el-icon-s-custom',
103: 'el-icon-s-check',
101: 'el-icon-s-goods',
102: 'el-icon-s-order',
145: 'el-icon-s-marketing'
},
isCollapse: false,
// 被激活的链接地址
activePath: ''
}
},
created() {
this.getMenuList()
this.activePath = window.sessionStorage.getItem('activePath')
},
methods: {
logout() {
window.sessionStorage.clear()
this.$router.push('/login')
this.$message.warning('已退出')
},
// 获取所有的菜单
async getMenuList() {
const {
data: result } = await this.$http.get('menus')
if (result.meta.status !== 200) return this.$message.error(result.meta.msg)
this.menulist = result.data
console.log(result)
},
// 点击按钮切换菜单折叠与展开
toggleCollapse() {
this.isCollapse = !this.isCollapse
},
// 保存链接的激活状态
saveNavState(activePath) {
window.sessionStorage.setItem('activePath', activePath)
this.activePath = activePath
}
}
}
script>
<style scoped>
.home_container {
height: 100%;
}
.el-header {
background-color: #373d41;
display: flex;
justify-content: space-between;
padding-left: 0;
align-items: center;
color: #fff;
font-size: 20px;
}
.el-header > div {
display: flex;
align-items: center;
}
.el-header > div > span {
margin-left: 15px;
}
.el-aside {
background-color: #333744;
}
.toggle-button {
background-color: #4A5064;
font-size: 10px;
line-height: 24px;
color: rgb(144,147,153);
text-align: center;
letter-spacing: 0.2em;
cursor: pointer
}
.el-menu {
border-right: none;
}
.el-main {
background-color: #eaedf1;
}
style>