国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Vue+Element UI 權(quán)限管理(角色 )

這篇具有很好參考價值的文章主要介紹了Vue+Element UI 權(quán)限管理(角色 )。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

用戶前臺登錄后,后臺返回一個token,將該token存儲到store中,并設(shè)置到header中,每次發(fā)起請求時都會攜帶該token,用于后臺進行權(quán)限校驗

// 登錄方法 login.vue
 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 {
          console.log("error submit!!");
          return false;
        }
      });
    },

在store 的user.js中定義了該方法

 login({ commit }, userInfo) {
    const { userName, userPassword } = userInfo;
    return new Promise((resolve, reject) => {
      login({ userName: userName.trim(), userPassword: userPassword })
        .then((response) => {
          const { data } = response;
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_AUTHORITIES: (state, authorities) => {
    state.authorities = authorities;
  },
};

此時登錄成功后,后臺將返回一個token

element 權(quán)限管理,前端學(xué)習(xí),vue.js,elementui

在請求攔截器中將token添加到請求頭上,在響應(yīng)攔截器中設(shè)置未登錄狀態(tài)訪問時跳轉(zhuǎn)到登錄頁面

import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken, removeToken } from "@/utils/auth";
import router from "@/router";

// create an axios instance
const service = axios.create({
  baseURL: "http://localhost:8080", // url = base url + request url
  timeout: 5000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers["token"] = getToken();
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

//  response 攔截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200 && res.code !== 201) {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 5 * 1000,
      });

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm(
          "You have been logged out, you can cancel to stay on this page, or log in again",
          "Confirm logout",
          {
            confirmButtonText: "Re-Login",
            cancelButtonText: "Cancel",
            type: "warning",
          }
        ).then(() => {
          store.dispatch("user/resetToken").then(() => {
            location.reload();
          });
        });
      }
      if (res.code == 401) {
        removeToken();
        router.replace({
          path: "/login",
        });
      }
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;

?在permission.js 中進行相關(guān)代碼編寫 (獲取用戶的信息,動態(tài)路由的生成加載)

?router.beforeEach()路由攔截()

import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login"]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  // determine whether the user has logged in
  const hasToken = getToken();
  const hasRoles =
    store.state.user.authorities && store.state.user.authorities.length > 0;
  // 如果有token再跳轉(zhuǎn)到登錄頁面時,根據(jù)獲取的角色信息進行頁面跳轉(zhuǎn)
  if (hasToken) {
    if (to.path === "/login") {
      if (store.state.user.authorities) {
        if (store.state.user.authorities.includes("ROLE_ADMIN")) {
          next({ path: "/" });
        } else {
          next({ path: "/user" });
        }
      } else {
        next({ path: "/" });
      }
      NProgress.done();
    } else {
      // 獲取登錄用戶名 如果用戶名存在說明用戶已經(jīng)登錄且獲得了用戶信息,直接放行,如果沒有用戶名,就進行用戶信息獲取
      const hasGetUserInfo = store.getters.name;
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          //判斷用戶角色是否存在
          if (!hasRoles) {
            let userInfo = await store.dispatch("user/getInfo"); // 獲取用戶信息
            // 根據(jù)獲得到的用戶信息,獲取用戶角色信息并動態(tài)生成路由
            let routes = await store.dispatch(
              "permission/getAsyncRoutes",
              userInfo.user.authorities
            );
            router.options.routes = routes;
            router.addRoutes(routes); // 將生成的動態(tài)路由添加到原先的路由中
            next({ ...to, replace: true }); // 保證路由已掛載

            // 根據(jù)用戶角色進行登錄后的首頁面跳轉(zhuǎn)
            if (store.state.user.authorities) {
              if (store.state.user.authorities.includes("ROLE_ADMIN")) {
                next({ path: "/" });
              } else {
                next({ path: "/user/user" });
              }
            }
          }
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch("user/resetToken");
          Message.error(error || "Has Error");
          next(`/login`);
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});

獲取用信息的方法定義在store的user.js中

  // 獲取用戶信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response) => {
          const { data } = response;
          if (!data) {
            return reject("Verification failed, please Login again.");
          }
          const { username, authorities } = data.user;
          // 將用戶名,和用戶角色信息存儲到store中
          commit("SET_NAME", username); 
          commit("SET_AUTHORITIES", authorities);
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

在store 的?permission.js 為動態(tài)路由的相關(guān)方法和存儲?

import { asyncRoutes, constantRoutes } from "@/router";
/**
 * 通過meta中的roles信息判斷用戶是否有權(quán)限
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

/**
 * 根據(jù)角色和配置生成當(dāng)前用戶的路由
 * @param {array} routes 配置的路由
 * @param {array} roles 用戶角色
 */
let GenerateRoutes = (routes, roles) => {
  let res = [];
  routes.forEach((route) => {
    const tmp = { ...route };

    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = GenerateRoutes(tmp.children, roles);
      }
      // console.log(tmp);
      res.push(tmp);
    }
  });

  return res;
};

const getDefaultState = () => {
  return {
    roles: [],
    routes: constantRoutes, // 用于配置頁面導(dǎo)航等
  };
};
const state = getDefaultState();
const mutations = {
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes;
  },
};

const actions = {
  /**根據(jù)角色獲取路由配置 */
  getAsyncRoutes({ commit }, roles) {
    let filterRoutes = GenerateRoutes(asyncRoutes, roles);
    let res = constantRoutes.concat(filterRoutes);
    commit("SET_ROUTES", res);
    return res;
  },
};

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

將新增的js文件引入store的index.js文件中

import Vue from "vue";
import Vuex from "vuex";
import getters from "./getters";
import app from "./modules/app";
import settings from "./modules/settings";
import user from "./modules/user";
import permission from "./modules/permission"; 

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    app,
    settings,
    user,
    permission, 
  },
  getters,
});

export default store;

路由文件

import Vue from "vue";
import Router from "vue-router";

Vue.use(Router);

/* Layout */
import Layout from "@/layout";

// 默認路由
export const constantRoutes = [
  {
    path: "/login",
    component: () => import("@/views/login/index"),
    hidden: true,
  },
  {
    path: "/404",
    component: () => import("@/views/404"),
    hidden: true,
  },
];
// 自定義動態(tài)路由,在meta中添加了roles,通過roles中是角色進行動態(tài)生成不同角色的動態(tài)路由
export const asyncRoutes = [
  {
    path: "/",
    component: Layout,
    redirect: "/employee",
    meta: { roles: ["ROLE_ADMIN"] },
    children: [
      {
        path: "employee",
        name: "Employee",
        component: () => import("@/views/employee/index"),
        // meta: { title: "員工管理", icon: "el-icon-s-custom" },
        meta: {
          roles: ["ROLE_ADMIN"],
          title: "員工管理",
          icon: "el-icon-s-custom",
        },
      },
    ],
  },
 {
    path: "/user",
    component: Layout,
    meta: { roles: ["ROLE_DEPT", "ROLE_EMP"] },
    children: [
      {
        path: "user",
        name: "User",
        component: () => import("@/views/user/index"),
        meta: {
          roles: ["ROLE_DEPT", "ROLE_EMP"],
          title: "個人信息",
          icon: "el-icon-setting",
        },
      },
    ],
  },
// 404 page must be placed at the end !!!
  { path: "*", redirect: "/404", hidden: true },
];

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

const router = createRouter();

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher; // reset router
}

export default router;

?此時登錄成功并獲取到用戶信息后,可在控制臺看到存儲到store中的信息

element 權(quán)限管理,前端學(xué)習(xí),vue.js,elementui

?登錄成功界面實例

管理員

element 權(quán)限管理,前端學(xué)習(xí),vue.js,elementui

部門經(jīng)理

element 權(quán)限管理,前端學(xué)習(xí),vue.js,elementui

基本員工文章來源地址http://www.zghlxwxcb.cn/news/detail-518902.html

到了這里,關(guān)于Vue+Element UI 權(quán)限管理(角色 )的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • Vue + Element UI 前端篇(八):管理應(yīng)用狀態(tài)

    Vue + Element UI 前端篇(八):管理應(yīng)用狀態(tài)

    1. 引入背景 像先前我們是有導(dǎo)航菜單欄收縮和展開功能的,但是因為組件封裝的原因,隱藏按鈕在頭部組件,而導(dǎo)航菜單在導(dǎo)航菜單組件,這樣就涉及到了組件收縮狀態(tài)的共享問題。收縮展開按鈕觸發(fā)收縮狀態(tài)的修改,導(dǎo)航菜單需要根據(jù)收縮狀態(tài)來設(shè)置導(dǎo)航欄的寬度。這樣就

    2024年02月09日
    瀏覽(51)
  • 管理系統(tǒng)的前端模板(vue2+Element UI)

    管理系統(tǒng)的前端模板(vue2+Element UI)

    目錄 前言 一、模板展示圖 二、獲取的方式及操作運行步驟? (一)獲取方式 (二)操作步驟? 1.下載安裝node.js? 2.下載完成解壓縮后在idea的里面打開終端。 3.輸入下載相關(guān)依賴的命令 4.運行項目的命令 5.然后把給到的地址瀏覽器打開就可以了 ?三、代碼的展示(這個點的內(nèi)

    2024年02月05日
    瀏覽(31)
  • 【前端】Vue+Element UI案例:通用后臺管理系統(tǒng)-面包屑、tag欄

    【前端】Vue+Element UI案例:通用后臺管理系統(tǒng)-面包屑、tag欄

    參考視頻: VUE項目,VUE項目實戰(zhàn),vue后臺管理系統(tǒng),前端面試,前端面試項目 案例 鏈接 【前端】Vue+Element UI案例:通用后臺管理系統(tǒng)-導(dǎo)航欄(視頻p1-16) https://blog.csdn.net/karshey/article/details/127640658 【前端】Vue+Element UI案例:通用后臺管理系統(tǒng)-Header+導(dǎo)航欄折疊(p17-19) http

    2024年02月09日
    瀏覽(64)
  • Vue3+Vue-Router+Element-Plus根據(jù)后端數(shù)據(jù)實現(xiàn)前端動態(tài)路由——權(quán)限管理模塊

    Vue3+Vue-Router+Element-Plus根據(jù)后端數(shù)據(jù)實現(xiàn)前端動態(tài)路由——權(quán)限管理模塊

    提示:文章內(nèi)容仔細看一些,或者直接粘貼復(fù)制,效果滿滿 提示:文章大概 1、項目:前后端分離 2、前端:基于Vite創(chuàng)建的Vue3項目 3、后端:沒有,模擬的后端數(shù)據(jù) 4、關(guān)于路徑“@”符號——vite.config.js 文件里修改 提示:以下是本篇文章正文內(nèi)容,下面案例可供復(fù)制粘貼使用

    2024年02月02日
    瀏覽(123)
  • 前端Vue:權(quán)限管理,給角色分配權(quán)限

    前端Vue:權(quán)限管理,給角色分配權(quán)限

    ??前端-Vue權(quán)限控制,菜單權(quán)限,按鈕權(quán)限_一人創(chuàng)客的博客-CSDN博客 目錄 介紹: 前端權(quán)限的概念: 前端權(quán)限的意義: Vue權(quán)限管理的代碼實現(xiàn): 菜單 刷新界?菜單消失 標(biāo)識?戶名, ?便查看當(dāng)前?戶 退出登陸:? 界面: 1.判斷當(dāng)前是否登陸 2.控制是否可以訪問角色界面 (

    2024年02月11日
    瀏覽(18)
  • (vue權(quán)限管理)前端路由表角色權(quán)限管理,通過登錄不同角色側(cè)邊欄顯示對應(yīng)頁面

    (vue權(quán)限管理)前端路由表角色權(quán)限管理,通過登錄不同角色側(cè)邊欄顯示對應(yīng)頁面

    1. 首先在src/router/index.js中添加路由表,其中constantRoutes 設(shè)置的為所有角色可見的路由,asyncRouterMap為對應(yīng)權(quán)限人員可見路由,demo路由表代碼如下: 2.在src/api/user.js中創(chuàng)建用戶登錄,獲取用戶信息,以及登出的接口 3.在store/modules/user.js文件,添加獲取角色權(quán)限r(nóng)ole的信息 4.在src

    2024年02月11日
    瀏覽(23)
  • 【Vue2+Element ui通用后臺】菜單權(quán)限

    對于菜單權(quán)限我們需要解決以下問題: 1、不同的賬號登錄,有不同的菜單 2、通過輸入url地址來顯示頁面,所以應(yīng)該根據(jù)權(quán)限動態(tài)注冊路由 3、對于菜單數(shù)據(jù),在不同頁面之間的數(shù)據(jù)通信 現(xiàn)在項目中的菜單,我們是在 CommenAside 中寫死的,現(xiàn)在我們需要根據(jù)登錄后返回的權(quán)限

    2024年02月07日
    瀏覽(20)
  • 基于vue-cli創(chuàng)建后臺管理系統(tǒng)前端頁面——element-ui,axios,跨域配置,布局初步,導(dǎo)航欄

    基于vue-cli創(chuàng)建后臺管理系統(tǒng)前端頁面——element-ui,axios,跨域配置,布局初步,導(dǎo)航欄

    1.vue-cli創(chuàng)建前端工程,安裝element-ui,axios和配置; 2.前端跨域的配置,請求添加Jwt的設(shè)置; 3.進行初始化布局,引入新增頁面的方式; 4.home頁面導(dǎo)航欄的設(shè)置,一級目錄,二級目錄; 安裝成功 布局初步 1.vue-cli創(chuàng)建前端工程,安裝element-ui,axios和配置; 2.前端跨域的配置,請

    2024年02月09日
    瀏覽(34)
  • ?Vue + Element UI前端篇(二):Vue + Element 案例 ?

    ?Vue + Element UI前端篇(二):Vue + Element 案例 ?

    打開 Visual Studio Code,F(xiàn)ile -- add Folder to Workspace,導(dǎo)入我們的項目。 安裝依賴 Element 是國內(nèi)餓了么公司提供的一套開源前端框架,簡潔優(yōu)雅,提供了 vue、react、angular 等多個版本,我們這里使用 vue 版本來搭建我們的界面。 訪問:http://element-cn.eleme.io/#/zh-CN/component/installation?,官

    2024年02月09日
    瀏覽(25)
  • 78.(前端)分配權(quán)限頁面顯示——樹形結(jié)構(gòu)使用(Element-ui的Tree樹形控件)

    78.(前端)分配權(quán)限頁面顯示——樹形結(jié)構(gòu)使用(Element-ui的Tree樹形控件)

    在前端的操作中,應(yīng)該增加修改、刪除、分配權(quán)限的操作 這次主要是實現(xiàn)分配權(quán)限的顯示?。。。。。?更換icon圖標(biāo),并設(shè)計大小 綁定函數(shù),點擊彈出提示框(DIalog對話框) 在對話框內(nèi),應(yīng)該顯示一個樹形結(jié)構(gòu)提供選擇(Tree樹形控件) 初始化樹形結(jié)構(gòu),并填充數(shù)據(jù)

    2024年02月05日
    瀏覽(87)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包