程序员的资源宝库

网站首页 > gitee 正文

vue-element-admin框架学习笔记

sanyeah 2024-03-30 13:09:07 gitee 5 ℃ 0 评论

0 背景

vue-element-admin是一个已高度完成的系统原型,它基于vue框架和elementUI组件库。它使用最新的前端技术栈,内置i18n国际化解决方案、动态路由、权限验证。它可以帮助我们快速搭建企业级中后台系统原型。

源码地址:https://github.com/PanJiaChen/vue-element-admin。

而且在源码页面的markdown文档中给出了系统预览链接:https://panjiachen.github.io/vue-element-admin。(国内建议访问这个链接:https://panjiachen.gitee.io/vue-element-admin)

还给出了指导文档:https://panjiachen.github.io/vue-element-admin-site/zh/guide/。国内建议访问这个链接:(https://panjiachen.gitee.io/vue-element-admin-site/zh/)

还有一系列教程文章:https://juejin.cn/post/6844903476661583880。见下面截图所示

 

 vue相关教程,可参考:https://www.cnblogs.com/zhenjingcool/p/16827020.html

代码结构

1 代码解读

注:某些地方已经在源码基础上做了自己的修改,所以可能和源码有所出入

1 入口js

这个项目中,入口js是src/main.js,为什么入口文件是main.js?参考https://www.cnblogs.com/zhenjingcool/p/16827020.html 23.5小节对 vue-cli-service的介绍。

import Vue from 'vue'

import Cookies from 'js-cookie'

import 'normalize.css/normalize.css' // a modern alternative to CSS resets

import Element from 'element-ui'
import './styles/element-variables.scss'
import enLang from 'element-ui/lib/locale/lang/en'// 如果使用中文语言包请默认支持,无需额外引入,请删除该依赖

import '@/styles/index.scss' // global css

import App from './App'
import store from './store'
import router from './router'

import './icons' // icon
import './permission' // permission control
import './utils/error-log' // error log

import * as filters from './filters' // global filters

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
if (process.env.NODE_ENV === 'production') {
  const { mockXHR } = require('../mock')
  mockXHR()
}

Vue.use(Element, {
  size: Cookies.get('size') || 'medium', // set element-ui default size
  locale: enLang // 如果使用中文,无需设置,请删除
})

// register global utility filters
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

在这个js中导入了vue框架、element-ui组件库,以及根组件App.vue、Vuex.store、VueRouter

import Vue from 'vue'
import Element from 'element-ui'
import App from './App'
import store from './store'
import router from './router'

其中Vuex.store是用来集中式存储管理所有组件的状态,教程可参考:https://blog.csdn.net/qq_56989560/article/details/124706021

根组件App.vue代码如下:

<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

Vue.use(Element)的作用是安装插件,这里的插件是Element,后台会执行插件的install方法。比如element的alert是这样被导入到vue中的

Alert.install = function(Vue) {
  Vue.component(Alert.name, Alert);
};

这里在vue中注册一个全局组件Alert。

其他element中的组件也是这样注册到vue的。

接下来进行根组件App.vue的挂载,挂载到<div id="app">

实例化Vue组件时传递的参数是一个对象

{
  el: '#app',
  router,
  store,
  render: h => h(App)
}

其中router为路由组件,store用于存储组件状态,render: h => h(App)为一个函数,这个函数被重命名为render,下面我们看一下这个函数h => h(App),在vue里h函数是createElement函数的别名,所以说,这个函数等价于createElement => createElement(App),参考:https://blog.csdn.net/qq_22182989/article/details/122448873。

 

ps:为什么在创建vue实例new Vue时需要传递router这个option呢?参考:https://blog.csdn.net/m0_51513185/article/details/109096206

 

我们实例化了Vue组件并成功挂载之后,vue-router将会起作用,这时会进行路由跳转,而路由跳转时会做一些权限验证,见下面的permission.js。

接下来,我们看一下这个import import './permission' ,这里导入了permission.js这个js。作用是权限控制

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', '/auth-redirect'] // 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()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')

          console.log('roles', roles)

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          console.log('accessRoutes', accessRoutes)

          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          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?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

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

其中 router.beforeEach 和 router.afterEach 是vue中两个全局的路由钩子函数,分别用于在进入某个路由前后做一些必要的处理操作,比如权限验证、token验证等。参考:https://www.cnblogs.com/huayang1995/p/13818732.html

在permission.js中,首先判断token是否存在,如果token不存在,则会跳转到登陆页面。

如果token存在,则会继续判断当前请求是否是登陆页,如果是登陆页,则直接会跳转到首页,如果不是登陆页,则从Vues中拿到用户信息,如果拿到用户信息,则请求哪个路由就跳转到哪个路由对应的页面,如果用户信息不存在,说明用户刚刚登陆,此时将请求/user/info接口获取用户信息,然后通过Vuex设置用户信息,设置好之后跳转到路由对应的页面。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 小点:

代码根路径下的public文件夹:放在public静态资源文件夹下的文件,webpack打包不会对其处理,直接把文件复制到存放项目的工程目录下。我们可以把一些静态图片放到这里,vue组件中引用的方式为:

<img :src="'/admin.gif?imageView2/1/w/80/h/80'" class="user-avatar">

上面是Navbar.vue组件中的代码,因为public路径不编译,所以,编译后这个路径下的文件会被原样拷贝到编译目录根路径下,所以,我们引用直接在根路径下引用就可以

持续更新中...

 

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表