退出登录
_vue 页面部分路由更改">
当前位置:   article > 正文

01---vue+element+admin将本地路由修改为权限路由_vue 页面部分路由更改

vue 页面部分路由更改

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

src/views/cache/index.vue

  1. <template>
  2. <div class="index">
  3. <div class="logout">
  4. <el-button type="danger" @click="handelLogout">退出登录</el-button>
  5. </div>
  6. <div class="index_box">
  7. <ul>
  8. <li
  9. v-for="item in indexArray"
  10. :key="item.id"
  11. :style="{ background: item.color }"
  12. @click="handeClickName(item)"
  13. >
  14. {{ item.title }}
  15. </li>
  16. </ul>
  17. </div>
  18. </div>
  19. </template>
  20. <script>
  21. export default {
  22. data() {
  23. return {
  24. indexArray: [
  25. {
  26. title: "组件系统",
  27. id: 1,
  28. color: "#36cafb",
  29. },
  30. {
  31. title: "图表系统",
  32. id: 2,
  33. color: "#6aabc5",
  34. },
  35. {
  36. title: "表格系统",
  37. id: 3,
  38. color: "#0083b7",
  39. },
  40. {
  41. title: "多级路由",
  42. id: 4,
  43. color: "#49f489",
  44. },
  45. ],
  46. };
  47. },
  48. methods: {
  49. // 退出登录
  50. async handelLogout() {
  51. await this.$store.dispatch("user/logout");
  52. this.$router.push("/login");
  53. },
  54. // 点击模块名称
  55. async handeClickName(data) {
  56. // 点击调用vuex中的方法将名称保存到cooike中
  57. await this.$store.dispatch("user/getNickName", data.title);
  58. //存储后跳转到首页
  59. this.$router.push("/");
  60. // 调用全局挂载的方法,关闭所有标签页
  61. this.$store.dispatch("tagsView/delAllViews", null, { root: true });
  62. },
  63. },
  64. };
  65. </script>
  66. <style scoped>
  67. ul,
  68. li {
  69. padding: 0px;
  70. margin: 0px;
  71. list-style-type: none;
  72. }
  73. ul {
  74. width: 1200px;
  75. display: flex;
  76. justify-content: space-between;
  77. text-align: center;
  78. color: #fff;
  79. font-size: 32px;
  80. font-weight: 500;
  81. position: fixed;
  82. top: calc(50% - 75px);
  83. left: calc(50% - 600px);
  84. }
  85. li {
  86. width: 300px;
  87. height: 150px;
  88. line-height: 150px;
  89. cursor: pointer;
  90. }
  91. .index {
  92. width: 100%;
  93. height: 100%;
  94. background: #252e4b;
  95. }
  96. .logout .el-button {
  97. position: fixed;
  98. top: 20px;
  99. right: 50px;
  100. }
  101. </style>

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

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

  1. import Cookies from 'js-cookie'
  2. // 定义存储在cookie的token名称
  3. const TokenKey = 'admin-token'
  4. // 定义存储在cookie的模块名称
  5. const NickName = 'nick-name'
  6. export function getToken() {
  7. return Cookies.get(TokenKey)
  8. }
  9. export function setToken(token) {
  10. return Cookies.set(TokenKey, token)
  11. }
  12. export function removeToken() {
  13. return Cookies.remove(TokenKey)
  14. }
  15. export function getNickName() {
  16. return Cookies.get(NickName)
  17. }
  18. export function setNickName(nickName) {
  19. return Cookies.set(NickName, nickName)
  20. }
  21. export function removeNickName() {
  22. return Cookies.remove(NickName)
  23. }

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

  1. import { login, logout, getInfo } from '@/api/user'
  2. import { getToken, setToken, removeToken, getNickName, setNickName, removeNickName } from '@/utils/auth'
  3. import router, { resetRouter } from '@/router'
  4. const state = {
  5. token: getToken(),
  6. name: '',
  7. avatar: '',
  8. introduction: '',
  9. roles: [],
  10. nickName: getNickName(),
  11. }
  12. const mutations = {
  13. SET_TOKEN: (state, token) => {
  14. state.token = token
  15. },
  16. SET_INTRODUCTION: (state, introduction) => {
  17. state.introduction = introduction
  18. },
  19. SET_NAME: (state, name) => {
  20. state.name = name
  21. },
  22. SET_AVATAR: (state, avatar) => {
  23. state.avatar = avatar
  24. },
  25. SET_ROLES: (state, roles) => {
  26. state.roles = roles
  27. },
  28. SET_NICK_NAME: (state, nickName) => {
  29. state.nickName = nickName
  30. }
  31. }
  32. const actions = {
  33. // user login
  34. login({ commit }, userInfo) {
  35. const { username, password } = userInfo
  36. return new Promise((resolve, reject) => {
  37. login({ username: username.trim(), password: password }).then(response => {
  38. const { data } = response
  39. commit('SET_TOKEN', data.token)
  40. setToken(data.token)
  41. resolve()
  42. }).catch(error => {
  43. reject(error)
  44. })
  45. })
  46. },
  47. // get user info
  48. getInfo({ commit, state }) {
  49. return new Promise((resolve, reject) => {
  50. getInfo(state.token).then(response => {
  51. const { data } = response
  52. if (!data) {
  53. reject('Verification failed, please Login again.')
  54. }
  55. const { roles, name, avatar, introduction } = data
  56. // roles must be a non-empty array
  57. if (!roles || roles.length <= 0) {
  58. reject('getInfo: roles must be a non-null array!')
  59. }
  60. commit('SET_ROLES', roles)
  61. commit('SET_NAME', name)
  62. commit('SET_AVATAR', avatar)
  63. commit('SET_INTRODUCTION', introduction)
  64. resolve(data)
  65. }).catch(error => {
  66. reject(error)
  67. })
  68. })
  69. },
  70. // 将nick-name放入到vuex中
  71. getNickName({ commit }, nickName) {
  72. return new Promise((resolve, reject) => {
  73. commit('SET_NICK_NAME', nickName)
  74. setNickName(nickName)
  75. resolve()
  76. }).catch(error => {
  77. reject(error)
  78. })
  79. },
  80. // user logout
  81. logout({ commit, state, dispatch }) {
  82. return new Promise((resolve, reject) => {
  83. logout(state.token).then(() => {
  84. commit('SET_TOKEN', '')
  85. commit('SET_ROLES', [])
  86. commit('SET_NICK_NAME', '')
  87. removeToken()
  88. resetRouter()
  89. removeNickName()
  90. // reset visited views and cached views
  91. // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
  92. dispatch('tagsView/delAllViews', null, { root: true })
  93. resolve()
  94. }).catch(error => {
  95. reject(error)
  96. })
  97. })
  98. },
  99. cache({ commit, state, }) {
  100. return new Promise((resolve, reject) => {
  101. logout(state.token).then(() => {
  102. commit('SET_ROLES', [])
  103. commit('SET_NICK_NAME', '')
  104. resetRouter()
  105. removeNickName()
  106. resolve()
  107. }).catch(error => {
  108. reject(error)
  109. })
  110. })
  111. },
  112. // remove token
  113. resetToken({ commit }) {
  114. return new Promise(resolve => {
  115. commit('SET_TOKEN', '')
  116. commit('SET_ROLES', [])
  117. commit('SET_NICK_NAME', '')
  118. removeToken()
  119. resolve()
  120. removeNickName()
  121. })
  122. },
  123. // dynamically modify permissions
  124. async changeRoles({ commit, dispatch }, role) {
  125. const token = role + '-token'
  126. commit('SET_TOKEN', token)
  127. setToken(token)
  128. const { roles } = await dispatch('getInfo')
  129. resetRouter()
  130. // generate accessible routes map based on roles
  131. const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
  132. // dynamically add accessible routes
  133. router.addRoutes(accessRoutes)
  134. // reset visited views and cached views
  135. dispatch('tagsView/delAllViews', null, { root: true })
  136. }
  137. }
  138. export default {
  139. namespaced: true,
  140. state,
  141. mutations,
  142. actions
  143. }

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

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

  1. import Vue from 'vue'
  2. import Router from 'vue-router'
  3. Vue.use(Router)
  4. /* Layout */
  5. import Layout from '@/layout'
  6. /**
  7. * Note: sub-menu only appear when route children.length >= 1
  8. * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
  9. *
  10. * hidden: true if set true, item will not show in the sidebar(default is false)
  11. * alwaysShow: true if set true, will always show the root menu
  12. * if not set alwaysShow, when item has more than one children route,
  13. * it will becomes nested mode, otherwise not show the root menu
  14. * redirect: noRedirect if set noRedirect will no redirect in the breadcrumb
  15. * name:'router-name' the name is used by <keep-alive> (must set!!!)
  16. * meta : {
  17. roles: ['admin','editor'] control the page roles (you can set multiple roles)
  18. title: 'title' the name show in sidebar and breadcrumb (recommend set)
  19. icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
  20. noCache: true if set true, the page will no be cached(default is false)
  21. affix: true if set true, the tag will affix in the tags-view
  22. breadcrumb: false if set false, the item will hidden in breadcrumb(default is true)
  23. activeMenu: '/example/list' if set path, the sidebar will highlight the path you set
  24. }
  25. */
  26. /**
  27. * constantRoutes
  28. * a base page that does not have permission requirements
  29. * all roles can be accessed
  30. */
  31. export const constantRoutes = [{
  32. path: '/redirect',
  33. component: Layout,
  34. hidden: true,
  35. children: [{
  36. path: '/redirect/:path(.*)',
  37. component: () =>
  38. import ('@/views/redirect/index')
  39. }]
  40. },
  41. {
  42. path: '/login',
  43. component: () =>
  44. import ('@/views/login/index'),
  45. hidden: true
  46. },
  47. {
  48. path: '/auth-redirect',
  49. component: () =>
  50. import ('@/views/login/auth-redirect'),
  51. hidden: true
  52. },
  53. {
  54. path: '/404',
  55. component: () =>
  56. import ('@/views/error-page/404'),
  57. hidden: true
  58. },
  59. {
  60. path: '/401',
  61. component: () =>
  62. import ('@/views/error-page/401'),
  63. hidden: true
  64. },
  65. {
  66. path: '/cache',
  67. component: () =>
  68. import ('@/views/cache/index'),
  69. hidden: true
  70. },
  71. {
  72. path: '/',
  73. component: Layout,
  74. redirect: '/dashboard',
  75. children: [{
  76. path: 'dashboard',
  77. component: () =>
  78. import ('@/views/dashboard/index'),
  79. name: 'Dashboard',
  80. meta: { title: '首页', icon: 'dashboard', affix: true }
  81. }]
  82. },
  83. {
  84. path: '/profile',
  85. component: Layout,
  86. redirect: '/profile/index',
  87. hidden: true,
  88. children: [{
  89. path: 'index',
  90. component: () =>
  91. import ('@/views/profile/index'),
  92. name: 'Profile',
  93. meta: { title: '个人中心', icon: 'user', noCache: true }
  94. }]
  95. }
  96. ]
  97. /**
  98. * asyncRoutes
  99. * 需要根据用户角色动态加载的路由
  100. */
  101. export const asyncRoutes = [
  102. { path: '*', redirect: '/404', hidden: true },
  103. ]
  104. // 创建路由
  105. const createRouter = () => new Router({
  106. // mode: 'history', // require service support
  107. scrollBehavior: () => ({ y: 0 }),
  108. routes: constantRoutes
  109. })
  110. const router = createRouter()
  111. // 重置路由
  112. export function resetRouter() {
  113. const newRouter = createRouter()
  114. router.matcher = newRouter.matcher // reset router
  115. }
  116. export default router

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

 

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

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/597930
推荐阅读