没有比这个更全的了吧,哈哈哈哈哈哈哈,话不多说,看代码
一、router文件下的index.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from '../views/Home.vue'
import login from '../views/login.vue'
import index from '../views/index.vue'
import personal from '../views/personal.vue'
Vue.use(Router)
var router = new Router({
routes:[
{
path: '/',
redirect: '/Login'
},
{
path: '/Login',
name: 'Login',
component: (resolve) => require(['@/views/login'],resolve)
},
{
path: '/Home',
name: 'Home',
meta: {
requireAuth: true
},
component: () => import( '@/views/Home'),
// component:Home,
children:[
{
path: '/index',
name: 'index',
meta: {
requireAuth: true
},
component: () => import( '@/views/index')
},
{
path: '/personal',
name: 'personal',
component: (resolve) => require(['@/views/personal'],resolve)
},
{
path: '/orderDetail',
name: 'orderDetail',
component: (resolve) => require(['@/views/orderDetail'],resolve)
}
]
}
]
})
router.$addRoutes = (params) => {
router.matcher = new Router({mode:'history'}).matcher
router.addRoutes(params)
}
export default router
二、router文件下新建一个关于动态路由的js文件(dongRouter.js)
import router from './index'
import store from './../store'
function createRouterDiGui (arr) {
const subRoutes = []
arr.forEach((item) => {
if (item.componentPath === '') {
subRoutes.push({
path: item.menuurl,
name: item.pathname,
meta: { requireAuth: true, menuId: item.menuId }
})
} else {
subRoutes.push({
path: item.menuurl,
name: item.pathname,
meta: { requireAuth: true, menuId: item.menuId },
component: resolve => require(['@/views/' + item.componentpath + ''], resolve)
})
}
// 判断是否有子数组
if (item.menuChilds.length && item.menuChilds.length > 0) {
//如果有子菜单,则再次执行创建路由方法(递归)
subRoutes.push(...createRouterDiGui(item.menuChilds))
}
})
return subRoutes
}
// 执行动态添加路由
function DynamicAddRouter () {
let subRoutes = []
subRoutes = createRouterDiGui(store.getters.getMenuInfo)
router.options.routes[2].children.push(...subRoutes)
console.log(router.options.routes[2].children)
router.options.routes.push(
{
path: '*',
name: '404',
component: (resolve) => require(['@/views/Page404'], resolve)
})
console.log(router.options.routes)
router.$addRoutes(router.options.routes)
}
export default {
DynamicAddRouter: DynamicAddRouter
}
三、main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import dongRouter from './router/dongRouter'
import store from './store'
import Axios from 'axios'
import Echars from 'echarts'
import './plugins/element.js'
Vue.prototype.$axios = Axios
Vue.prototype.$echars = Echars
Vue.config.productionTip = false
// 路由前置守卫(权限判断:判断对应路由是否登录,保证有些组件必须要在登录状态下才能显示)
router.beforeEach(function (to,from,next) {
// 如果用户去登录路由,则直接next
if(to.name === 'Login'){
next()
}else {
// 判断用户是否登录
if(to.meta.requireAuth){
// 如果登录
if(sessionStorage.getItem('isLogin')){
// 如果用户登录且刷新界面了,则重新添加动态路由
if(store.getters.getIsLogin && store.getters.getIsRefresh){
store.dispatch('setNoRefresh') // 改变刷新的状态,设为false,调用setNoRefresh
dongRouter.DynamicAddRouter() // 添加动态路由的方法
next({ ...to, replace: true })
}else {
next()
}
}else {
next({
path: '/Login'
})
}
}else {
if (store.getters.getIsRefresh) {
console.log('加载动态路由')
store.dispatch('setNoRefresh') // 重新刷新设置为false
dongRouter.DynamicAddRouter() // 添加动态路由的方法
next({ ...to, replace: true })
} else {
next()
}
}
}
})
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
四、store文件下的index.js(仓库)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 数据
const state = {
// 判断是否刷新
isRefresh:true,
// 判断是否登录
isLogin:window.sessionStorage.getItem('isLogin') ? Boolean(window.sessionStorage.getItem('menuInfo')) : false,
// 菜单数据
menuInfo:(window.sessionStorage.getItem('menuInfo')) ? JSON.parse(window.sessionStorage.getItem('menuInfo')) : [],
// 用户数据
employeeInfo:(window.sessionStorage.getItem('employeeInfo')) ? JSON.parse(window.sessionStorage.getItem('employeeInfo')) : [],
// token
token:(window.sessionStorage.getItem('token')) ? JSON.parse(window.sessionStorage.getItem('token')) : undefined
}
// 数据获取
const getters = {
getIsRefresh(state){
return state.isRefresh
},
getIsLogin(state){
return state.isLogin
},
getMenuInfo(state){
return state.menuInfo
},
getemployeeInfo(state){
return state.employeeInfo
},
getToken(state){
return state.token
}
}
// 行为,要执行的操作,如果有流程判断、异步请求也写在这里(主要是异步)
const actions = {
setNoRefresh ({ commit }) {
commit('setNoRefresh')
},
loginSuccess ({ commit }, data) {
commit('LoginSuccess', data)
},
LoginExit ({ commit }) {
commit('LoginExit')
}
}
// 处理状态的改变
const mutations = {
// 设置不刷新
setNoRefresh(state){
state.isRefresh = false
},
// 登录成功
LoginSuccess(state,data){
state.isLogin = true;
state.menuInfo = data.data[0].menuInfo;
state.employeeInfo = data.data[0].employeeInfo;
state.token = data.token;
window.sessionStorage.setItem('isLogin',true);
window.sessionStorage.setItem('menuInfo',JSON.stringify(data.data[0].menuInfo));
window.sessionStorage.setItem('token',JSON.stringify(data.token));
window.sessionStorage.setItem('employeeInfo',JSON.stringify(data.data[0].employeeInfo));
},
// 退出登录
LoginExit(){
state.isLogin = false;
state.menuInfo = [];
state.employeeInfo = [];
state.token = undefined;
window.sessionStorage.setItem('isLogin',false);
window.sessionStorage.removeItem('menuInfo');
window.sessionStorage.removeItem('employeeInfo');
window.sessionStorage.setItem('token',undefined);
}
}
const store = new Vuex.Store({
state,
getters,
actions,
mutations,
modules: {
}
})
export default store
五、登录组件(login.vue)
<script>
import dongRouter from './../router/dongRouter'
export default {
name: "login",
data() {
return {
checked: true,
formdata: {
username: '',
Pwd: ''
}
}
},
methods: {
login () {
var loginName = this.formdata.username
var loginPwd = this.formdata.Pwd
console.log(loginName)
console.log(loginPwd)
this.$axios.post('/api/employee/login', {
e_id: loginName,
e_password: loginPwd
},
{
headers: {
'Content-Type': 'application/json'
}
}).then((response) => {
console.log(response.data)
if (response.data.code !== 200) {
return this.$message.error(response.data.message)
} else {
this.$message.success('登录成功')
//将用户名放入vuex(dispatch 异步操作 this.$store.dispatch('actions的方法',arg))
//this.$store.dispatch('loginSuccess',response.data.data[0])
this.$store.dispatch('loginSuccess',response.data)
window.sessionStorage.setItem('e_icon',JSON.stringify(response.data.data[0].employeeInfo.e_icon));
dongRouter.DynamicAddRouter()
//打印login状态
// console.log(this.$store.state.isLogin)
//跳转到主页
that.$router.push('/index')
}
})
}
}
}
</script>
六、主页框架组件Home.vue中绑定菜单
1、html中
<!--导航侧边栏-->
<el-aside width="17%">
<!--绑定菜单相关数据,这里的Menu我才用了引用组件,具体组件内容看第七步-->
<Menu :menuList="getMenuInfo"></Menu>
</el-aside>
2、script中
<script>
import Menu from '../components/Menu.vue'
import { mapGetters,mapActions} from 'vuex'
export default {
name: 'Home',
components: {
Menu
},
computed:{
// 获取仓库store文件下index.js存储的菜单相关信息
...mapGetters(['getMenuInfo']),
}
}
</script>
七、Menu组件(Menu.vue),结合elementui来的
<template>
<div class="MenuBox">
<el-scrollbar style="height: 100%;">
<el-menu
:default-active="$route.path"
unique-opened="true"
router
mode="vertical"
text-color="rgb(71,71,71)"
active-text-color="rgb(1,179,163)"
v-if="menuList"
background-color="white"
@open="handleOpen"
@close="handleClose"
class="el-menu-vertical-demo menu">
<!--主页内容(主页我是默认让每个权限都可以看到,所以就直接写)-->
<router-link to='/index'>
<el-menu-item>
<i class="el-icon-house"></i>
<span slot="title">主页</span>
</el-menu-item>
</router-link>
<!--这里就是从后台获取的动态菜单了,也是用的一个组件,具体看第八步-->
<MenuTree :menuList="menuList"></MenuTree>
</el-menu>
</el-scrollbar>
</div>
</template>
<script>
import MenuTree from '../components/MenuTree.vue'
export default{
name: 'Menu',
components: {
MenuTree
},
data(){
return {}
},
props:{
menuList: {
type: Array,
required: false
}
},
methods: {
handleOpen(key, keyPath) {
console.log(key, keyPath);
},
handleClose(key, keyPath) {
console.log(key, keyPath);
}
}
}
</script>
<style scoped>
a {
text-decoration: none;
}
.router-link-active {
text-decoration: none;
}
.el-menu-item{
height: 80px;
line-height: 80px;
font-size: 22px;
color: rgb(167, 179, 182);
letter-spacing: 3px;
}
.el-menu-item:hover{
color: rgb(54, 57, 59) !important;
font-weight: bolder!important;
}
.el-menu-item.is-active {
background-image: linear-gradient(to right,rgb(255,255,255),rgb(206,255,251))!important;
}
.el-submenu__title.is-active {
background-image: linear-gradient(to right,rgb(255,255,255),rgb(206,255,251))!important;
}
.el-submenu__title{
transition: border-color .3s,background-color .3s,color .3s;
}
.MenuTreeBox .el-menu-item:hover [class^=el-icon-]{
color: rgb(54, 57, 59) !important;
font-weight: bolder!important;
}
.MenuBox{
padding-top: 50px;
height: 100%;
box-sizing: border-box;
}
.MenuBox .menu{
height: 1200px;
}
.el-scrollbar__wrap{
overflow-x: hidden;
}
</style>
八、MenuTree组件(MenuTree.vue),主要用了递归(调用自身组件,重点重点重点,重要的事情说三遍)
<template>
<div class="MenuTreeBox">
<template v-for='menu in menuList'>
<!--{{menu.menuChilds.length}}-->
<!--如果当前有子菜单,则显示子菜单el-submenu,并调用递归(调用自身组件)-->
<el-submenu v-if='menu.menuChilds.length>0' :index='menu.menuurl' :key="menu.menuid" >
<template slot="title">
<i v-if="menu.menulmgclass" :class="menu.menulmgclass"></i>
<span slot="title">{{ menu.menuname }}</span>
</template>
<!-- 调用自身组件-->
<MenuTree :menuList='menu.menuChilds'></MenuTree>
</el-submenu>
<!--如果没有子菜单,则显示一级菜单-->
<el-menu-item v-else :index='menu.menuurl' :key='menu.menuid'>
<i v-if="menu.menulmgclass" :class="menu.menulmgclass"></i>
<span slot="title">{{ menu.menuname }}</span>
</el-menu-item>
</template>
</div>
</template>
<script>
import MenuTree from '../components/MenuTree.vue'
import ElSubmenu from "../../../../myProject/project4/node_modules/element-ui/packages/menu/src/submenu";
export default{
components: {ElSubmenu,MenuTree},
name: 'MenuTree',
data(){
return {}
},
props:{
menuList: {
type: Array,
required: false
}
},
methods:{
}
}
</script>
<style>
.MenuTreeBox .el-submenu .el-menu-item,.MenuTreeBox .el-menu-item, .MenuTreeBox .el-submenu .el-submenu__title{
height: 90px;
line-height: 90px;
font-size: 22px;
color: rgb(167, 179, 182);
box-sizing: border-box;
}
.MenuTreeBox{
letter-spacing: 3px;
}
.MenuTreeBox .el-submenu [class^=el-icon-],.MenuTreeBox .el-menu-item [class^=el-icon-],.MenuBox .el-menu-item [class^=el-icon-]{
font-size: 25px;
color: rgb(167, 179, 182);
margin-left: -50px;
margin-right: 25px;
}
.MenuTreeBox .el-icon-user{
padding-left: 50px;
color: rgb(167, 179, 182);
}
.MenuTreeBox .el-icon-delete{
margin-left: -70px!important;
color: rgb(167, 179, 182);
}
.MenuBox .el-icon-house{
margin-left: -100px!important;
color: rgb(167, 179, 182);
}
.MenuTreeBox li.el-menu-item:hover,.MenuTreeBox .el-submenu__title:hover,.MenuBox .el-menu-item:hover{
background-color: rgb(235,239,255)!important;
background-image: linear-gradient(to right,rgb(255,255,255),rgb(206,255,251));
color: rgb(54, 57, 59) !important;
border-right: 3px solid rgb(15,185,169)!important;
font-weight: bolder!important;
}
.MenuTreeBox .el-submenu__title:hover [class^=el-icon-],.MenuTreeBox .el-menu-item:hover,.MenuBox .el-menu-item:hover,.MenuBox .el-menu-item:hover .el-icon-house{
color: rgb(54, 57, 59)!important;
}
</style>