01---vue+element+admin将本地路由修改为权限路由

这篇博客介绍了在Vue Element Admin项目中如何实现模块名称的Cookie存储,并在src/utils/auth.js和src/store/modules/user.js中定义相关方法。同时,展示了如何在src/router/index.js中设置隐藏路由和缓存路由,包括dashboard和个人中心页面的配置。文章还强调了动态路由的重要性,并提供了部分代码示例。
摘要由CSDN通过智能技术生成

1.在src/views新建一个cache文件夹,cache文件夹下创建一个index.vue文件

src/views/cache/index.vue

<template>
  <div class="index">
    <div class="logout">
      <el-button type="danger" @click="handelLogout">退出登录</el-button>
    </div>
    <div class="index_box">
      <ul>
        <li
          v-for="item in indexArray"
          :key="item.id"
          :style="{ background: item.color }"
          @click="handeClickName(item)"
        >
          {{ item.title }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      indexArray: [
        {
          title: "组件系统",
          id: 1,
          color: "#36cafb",
        },
        {
          title: "图表系统",
          id: 2,
          color: "#6aabc5",
        },
        {
          title: "表格系统",
          id: 3,
          color: "#0083b7",
        },
        {
          title: "多级路由",
          id: 4,
          color: "#49f489",
        },
      ],
    };
  },
  methods: {
    // 退出登录
    async handelLogout() {
      await this.$store.dispatch("user/logout");
      this.$router.push("/login");
    },
    // 点击模块名称
    async handeClickName(data) {
      // 点击调用vuex中的方法将名称保存到cooike中
      await this.$store.dispatch("user/getNickName", data.title);
      //存储后跳转到首页
      this.$router.push("/");
      // 调用全局挂载的方法,关闭所有标签页
      this.$store.dispatch("tagsView/delAllViews", null, { root: true });
    },
  },
};
</script>

<style scoped>
ul,
li {
  padding: 0px;
  margin: 0px;
  list-style-type: none;
}
ul {
  width: 1200px;
  display: flex;
  justify-content: space-between;
  text-align: center;
  color: #fff;
  font-size: 32px;
  font-weight: 500;
  position: fixed;
  top: calc(50% - 75px);
  left: calc(50% - 600px);
}
li {
  width: 300px;
  height: 150px;
  line-height: 150px;
  cursor: pointer;
}
.index {
  width: 100%;
  height: 100%;
  background: #252e4b;
}
.logout .el-button {
  position: fixed;
  top: 20px;
  right: 50px;
}
</style>

2.点击模块名称事件handeClickName中有一个cooike存储

在src/utils/auth.js文件中,定义cookie存储的模块名称和方法

import Cookies from 'js-cookie'

// 定义存储在cookie的token名称
const TokenKey = 'admin-token'

// 定义存储在cookie的模块名称
const NickName = 'nick-name'

export function getToken() {
    return Cookies.get(TokenKey)
}

export function setToken(token) {
    return Cookies.set(TokenKey, token)
}

export function removeToken() {
    return Cookies.remove(TokenKey)
}

export function getNickName() {
    return Cookies.get(NickName)
}

export function setNickName(nickName) {
    return Cookies.set(NickName, nickName)
}

export function removeNickName() {
    return Cookies.remove(NickName)
}

 在src/store/modules/user.js文件中,定义cookie存储的模块名称和方法

import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, getNickName, setNickName, removeNickName } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    nickName: getNickName(),
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
        state.introduction = introduction
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_NICK_NAME: (state, nickName) => {
        state.nickName = nickName
    }
}

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { username, password } = userInfo
        return new Promise((resolve, reject) => {
            login({ username: username.trim(), password: password }).then(response => {
                const { data } = response
                commit('SET_TOKEN', data.token)
                setToken(data.token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo(state.token).then(response => {
                const { data } = response

                if (!data) {
                    reject('Verification failed, please Login again.')
                }

                const { roles, name, avatar, introduction } = data

                // roles must be a non-empty array
                if (!roles || roles.length <= 0) {
                    reject('getInfo: roles must be a non-null array!')
                }

                commit('SET_ROLES', roles)
                commit('SET_NAME', name)
                commit('SET_AVATAR', avatar)
                commit('SET_INTRODUCTION', introduction)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 将nick-name放入到vuex中
    getNickName({ commit }, nickName) {
        return new Promise((resolve, reject) => {
            commit('SET_NICK_NAME', nickName)
            setNickName(nickName)
            resolve()
        }).catch(error => {
            reject(error)
        })
    },

    // user logout
    logout({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then(() => {
                commit('SET_TOKEN', '')
                commit('SET_ROLES', [])
                commit('SET_NICK_NAME', '')
                removeToken()
                resetRouter()
                removeNickName()

                // reset visited views and cached views
                // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
                dispatch('tagsView/delAllViews', null, { root: true })

                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    cache({ commit, state, }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then(() => {
                commit('SET_ROLES', [])
                commit('SET_NICK_NAME', '')
                resetRouter()
                removeNickName()
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_NICK_NAME', '')
            removeToken()
            resolve()
            removeNickName()
        })
    },

    // dynamically modify permissions
    async changeRoles({ commit, dispatch }, role) {
        const token = role + '-token'

        commit('SET_TOKEN', token)
        setToken(token)

        const { roles } = await dispatch('getInfo')

        resetRouter()

        // generate accessible routes map based on roles
        const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
            // dynamically add accessible routes
        router.addRoutes(accessRoutes)

        // reset visited views and cached views
        dispatch('tagsView/delAllViews', null, { root: true })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

3.在src/router/index.js中添加cache/index.vue的路由

 src/router/index.js;说明:hidden:true是隐藏路由,除了login、404、401、dashboard、profile等必要的路由之外,其他的都可以删除,不懂可以直接把原本的index.js文件代码全部删除,把下面的代码黏贴上去

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
    noCache: true                if set true, the page will no be cached(default is false)
    affix: true                  if set true, the tag will affix in the tags-view
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */

/**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
export const constantRoutes = [{
        path: '/redirect',
        component: Layout,
        hidden: true,
        children: [{
            path: '/redirect/:path(.*)',
            component: () =>
                import ('@/views/redirect/index')
        }]
    },
    {
        path: '/login',
        component: () =>
            import ('@/views/login/index'),
        hidden: true
    },
    {
        path: '/auth-redirect',
        component: () =>
            import ('@/views/login/auth-redirect'),
        hidden: true
    },
    {
        path: '/404',
        component: () =>
            import ('@/views/error-page/404'),
        hidden: true
    },
    {
        path: '/401',
        component: () =>
            import ('@/views/error-page/401'),
        hidden: true
    },
    {
        path: '/cache',
        component: () =>
            import ('@/views/cache/index'),
        hidden: true
    },
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children: [{
            path: 'dashboard',
            component: () =>
                import ('@/views/dashboard/index'),
            name: 'Dashboard',
            meta: { title: '首页', icon: 'dashboard', affix: true }
        }]
    },
    {
        path: '/profile',
        component: Layout,
        redirect: '/profile/index',
        hidden: true,
        children: [{
            path: 'index',
            component: () =>
                import ('@/views/profile/index'),
            name: 'Profile',
            meta: { title: '个人中心', icon: 'user', noCache: true }
        }]
    }
]

/**
 * asyncRoutes
 * 需要根据用户角色动态加载的路由
 */

export const asyncRoutes = [
    { path: '*', redirect: '/404', hidden: true },
]

// 创建路由
const createRouter = () => new Router({
    // mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
})

const router = createRouter()

// 重置路由
export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher // reset router
}

export default router

 dashboard(首页)是每个模块中都有的页面,点击模块默认跳转到dashboard,为共用页面,不能删除;profile(个人中心)路由也可以删除,看自己需求,下面就是profile的页面效果

 

 注:因为内容太多,后面的内容在我后面的几个博客里:

02---vue+element+admin将本地路由修改为动态路由_天尘不打野的博客-CSDN博客

03---vue+element+admin将本地路由修改为动态路由_天尘不打野的博客-CSDN博客

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值