Just to a new company, the leadership explaination gives a new project, is very simple and easy, background management system comprised so after graduate, so not what has built the background management system framework, such as renren – fast, the backend is useless, I can accompany him a little bit of nature, just I don’t know my way around the block also, Just used to practice, learn, the following is my development summary of a little experience, record. This article is based on ideas and will not write all the code

Basic work

First of all, the basic work of the background management system, login, sidebar, navigation bar, because the time is too tight, I will directly use the network already have the basic framework vue-admin-template, these things do not need to repeat, directly with the ready-made, mainly summarize the permissions related.

Menu List Design

In the Vue-admin-template framework, the sidebar is generated based on the route, so we only need to maintain the route with a menu list. We don’t need a separate sidebar to manage the route. In order to satisfy the parameters necessary to render the route, we need to tell the back end what parameters we need. The experienced backend knows what parameters to return, but if they happen to be inexperienced, we have to ask for them.

field meaning note
title The title Used for sidebar title display
icon icon Used for sidebar icon display
type type Distinguish directories/menus/buttons
parentId The parent id Record the parent-child relationship
name Route the name Necessary routing
path address The address of the address bar, used for jumping and displaying
url The module path The module is located in the path of the folder
identification Authorization id CRM: Customer :list
hidden Whether to render in the sidebar There are some routes that we need to be able to access that we don’t want in the sidebar

* The above lists only the required fields, such as creation time, creator, sorting, etc., which can be added by negotiation with the back end as required

Role assignment

With the menu in place, we can begin to develop a list of roles. The list of roles is just a matter of adding, deleting, and changing, but here are just a few points that we encounter.

Saved parameters and echoes when assigning menus to roles

save

Most backend management systems use element-UI, while menu displays use the El-Tree component of the element, because when rendering routes, you need to have a parent-child structure. When I am here to save the selected node enclosing $refs. MenuListTree. GetCheckedKeys (), and half the selected node enclosing $refs. MenuListTree. GetHalfCheckedKeys () are preserved

The echo

This is because the half-selected node is also saved during the saving. In the echo, if the half-selected node is selected, all its child nodes will also be selected. To solve this problem, we only need to determine whether the node is a child node

let menuId = res.data.menuId // back end returns id string '1,3,4,5,8,9'
let _arr = menuId.split(",").map(item= > {
  return +item; // The plus sign is used because each item in the string partition array is a string and needs to be converted to a number
});
_arr.map(item= > {
  // Obtain the tree that corresponds to the id
  let node = this.$refs.menuListTree.getNode(item);
  // Check whether the node is a child node (that is, whether the node is a final node), and if so, set the selected state
  if (node.isLeaf) {
    this.$refs.menuListTree.setChecked(node, true); }});Copy the code

Route guard judgment

Front end do permission, mainly rely on the operation route, this piece of thought for a long time, facts proved that good memory is not as good as to rely on writing, think for a long time do not understand, write down for a while to understand.

Obtains the user permission list and menu information

I post my code here, with comments on some of the small difficulties ENCOUNTERED

router.beforeEach(async (to, from, next) => {
  // The vue-admin-template progress bar
  NProgress.start();

  // Set the browser TAB title
  document.title = getPageTitle(to.meta.title);

  / / access token
  const hasToken = getToken();

  if (hasToken) {
    if (to.path === "/login") {
      // If you have logged in, redirect to the home page
      next({ path: "/" });
      NProgress.done();
    } else {
      const hasGetUserInfo = store.getters.name;
      if(! hasGetUserInfo) {try {
          // Obtain user information if no user information is available
          await store.dispatch("user/getInfo");
        } catch (error) {
          // If the user information fails to be obtained, the token is cleared and the home page is skipped
          await store.dispatch("user/resetToken");
          Message.error(error || "Failed to obtain user information");
          next(`/login? redirect=${to.path}`); NProgress.done(); }}// Check whether the route is loaded or whether you want to access the whitelist page
      if( router.options.isAddDynamicMenuRoutes || whiteList.indexOf(to.path) ! = = -1
      ) {
        next();
      } else {
        // Obtain user permission information and menu list
        menuApi
          .getListById({ id: store.getters.userId })
          .then(res= > {
            console.log(res);
            let menuList = res.data.menuList;
            let permissions = res.data.permission;
            // The back end returns all the menus, and the front end filters the menus with permissions according to permissions
            // Select routes or directories that have permission
            menuList = menuList.filter(item= > {
              return (
                permissions.indexOf(item.identifying) > -1 ||
                item.parentId === 0
              );
            });
            // Convert the data into a routing structure
            menuList.map(item= > {
              if (item.parentId === 0) {
                item.component = Layout;
              } else {
                item.component = _import(item.url);
              }
              item.meta = {
                title: item.title,
                icon: item.icon
              };
            });
            // Convert the route to a parent-child structure
            menuList = treeDataTranslate(menuList);
            console.log(menuList);
            menuList = menuList.filter(item= > {
              return item.children;
            });
            // Add the 404 route after the dynamic route is added to prevent the page from matching the 404 before the dynamic route is matched
            menuList.push({ path: "*".redirect: "/ 404".hidden: true });
            router.options.isAddDynamicMenuRoutes = true;
            router.addRoutes(menuList);
            // this.$router is not responsive, so manually inject the routing element into the routing objectrouter.options.routes.push(... menuList);// I don't know why to add the following, but I know that if you don't refresh it, it will 404😅
            if (from.name == null) {
              next(to);
            } else {
              next();
            }
          })
          .catch(err= > {
            console.log(err);
            next(`/login? redirect=${to.path}`); }); }}}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? redirect=${to.path}`); NProgress.done(); }}});Copy the code

Talented, please great god more advice, if there is a bad or not detailed, please comment area comments