单页面架构

1、目录

├─src
| ├─assets 静态资源文件
| ├─components 公共组件
| ├─icon svg 图标
| ├─layout 界面布局
| ├─router 路由文件
| ├─services 请求服务
| ├─store vuex
| ├─styles scss文件
| ├─utils 公共方法文件
| ├─views 模块文件

项目git地址:https://git.xxxx/vue-admin-zonst
项目脚手架git地址:https://git.xxxx/vue-admin-zonst/src/node-cli

2、环境配置

package.json

    "dev": "vue-cli-service serve",     // 对应文件.env.development
    "dev:sw": "vue-cli-service serve --mode sw",  // 对应文件.env.sw
    "dev:new": "vue-cli-service serve --mode new",  // 对应文件.env.new
    "build:prod": "vue-cli-service build",   // 对应文件.env.production
    "build:sw": "vue-cli-service build --mode prodsw",  // 对应文件.env. prodsw
    "build:new": "vue-cli-service build --mode prodnew", // 对应文件.env. prod new

注意:环境配置文件,主要需要NODE_ENV 和 VUE_APP_BASE_API,在请求服务文件apiURL中必须要和VUE_APP_BASE_API设置的一致,切换环境的时候需要用到 。 NODE_ENV 在打包正式环境关闭打印输出和判断正式和测试用到(只支持3种模式:development,production,test)

3、请求服务

项目开发api层架构
简单介绍下不同的地方:

// 配置不同模块api
  let accounts
  // 当测试环境时,可以切换为正式环境
  if (getIsUseMasterApiKey() === 'true' && process.env.NODE_ENV.indexOf('development') > -1) {
    accounts = apiURL['production'][name]
  } else {
    accounts = apiURL[process.env.VUE_APP_BASE_API][name]
  }

注意:myserver.postData('user', user)前面的‘user’必须要和apiUrl 的模块接口(user)对应上。

4、layout配置

settings

module.exports = {
  logo: 'component', // 配置logo 只处理了svg的
  title: 'Vue Admin Zonst', // 配置title
  breadcrumb: false, // 配置面包屑
  IsSearch: false, // 配置菜单搜索
  tagsView: false, // 配置导航标签
  Layout: false, // 配置布局 true 左右结果 false 上下结构
  fixedHeader: true, // 是否固定头部导航栏
  sidebarLogo: true, // 是否显示Logo和title
  navbarBackground: '#324151', // 头部导航栏背景颜色
  navbarColor: '#fff', // 头部导航栏字体和图标颜色
  isUnifiedLogin: true, // 是否统一登入
  isGameShow: true, // 是否展示游戏平台
  isSwitchEnvironment: process.env.NODE_ENV.indexOf('development') > -1 // 是否切换环境  isAPIRouter: true // 是否异步请求接口返回router
}

5、router 路由文件

1、文件生成路由
模块文件统一写在views/autoRouter 下面
包含文件夹的是嵌套路由(二级路由),
不包含的一级路由。建议使用文件夹来包含,可创建子文件夹,即使是一级路由也不会影响。
目前最多只支持二级路由的生成,所以在autoRouter中可以根据自己的需要,将文件按子模块新增文件夹(建立3级文件夹),是没有问题的。

如果需要3级路由,就自行配置路由文件就可以了,在router/modules下配置,该文件夹下的js文件会自动加载到router中

// 自动获取modules配置
const files = require.context('./modules', false, /\.js$/)
let tmp
files.keys().forEach(key => {
  tmp = files(key).default
})
const requireAllVueComponents = require.context('../views/autoRouter', true, /\.vue$/, 'lazy')
const routerList = []

requireAllVueComponents.keys().forEach((allVueComponentItem) => {
  const completeName = allVueComponentItem.match(/\w+\.vue$/, '')[0]
  const routerObj = {}
  routerObj.path = '/' + allVueComponentItem.replace(/\./, 'autoRouter').replace(/.vue$/, '')
  routerObj.name = completeName.replace(/.vue$/, '')
  routerObj.component = () => requireAllVueComponents(allVueComponentItem).default || requireAllVueComponents(allVueComponentItem)

  // router 子路径
  const routerChildren = {
    path: '',
    component: routerObj.component,
    name: routerObj.name,
    meta: {
      title: '',
      icon: '',
      permissionArray: []
    }
  }
  // router 路径
  const router = {
    path: '',
    component: Layout,
    meta: {
      title: '',
      icon: '',
      permissionArray: []
    },
    children: []
  }

  const routerArr = routerObj.path.split('/')
  let isSame = true
  // 过滤所有components下的子组件,无需生成路由
  if (routerArr.includes('common')) {
    return
  }
  // 初始化属性值
  const routerAttribute = function(name, attribute) {
    const init = {
      index: 1,
      icon: 'component',
      name: name,
      permission: [1, 2, 3],
      newTime: new Date()
    }
    if (attribute === 'newTime') {
      return (routerName[name] && routerName[name] !== '' && routerName[name][attribute]) ? new Date(routerName[name][attribute]) : init[attribute]
    }
    return (routerName[name] && routerName[name] !== '' && routerName[name][attribute]) ? routerName[name][attribute] : init[attribute]
  }
  // 设置父属性值
  const parentAttribute = (name) => {
    router.index = routerAttribute(name, 'index')
    router.meta.icon = routerAttribute(name, 'icon')
    router.meta.title = routerAttribute(name, 'name')
    router.meta.permissionArray = routerAttribute(name, 'permission')
    router.meta.newTime = routerAttribute(name, 'newTime')
  }
  // 设置子属性值
  const childrenAttribute = (name) => {
    routerChildren.index = routerAttribute(name, 'index')
    routerChildren.meta.icon = routerAttribute(name, 'icon')
    routerChildren.meta.title = routerAttribute(name, 'name')
    routerChildren.meta.newTime = routerAttribute(name, 'newTime')
    routerChildren.meta.permissionArray = routerAttribute(name, 'permission')
  }
  switch (routerArr.length) {
    case 3:
      // 当路由不是嵌套路径时 直接push到routerList中
      parentAttribute(routerObj.name)
      router.children.push(routerChildren)
      routerChildren.path = routerObj.path + ((routerName[routerObj.name] && routerName[routerObj.name] !== '' && routerName[routerObj.name]['isID'] && isGameShow) ? routerName[routerObj.name]['isID'] : '')
      childrenAttribute(routerObj.name)
      routerList.push(router)
      break
    case 4:
      // 当路由是嵌套路径时,如果routerList中包含改路径,则在children中加入子路径,否则在routerList中push。
      router.path = '/' + routerArr[1] + '/' + routerArr[2]
      router.name = routerArr[2] + 'p'
      parentAttribute(routerArr[2])
      routerChildren.path = routerArr[3] + ((routerName[routerObj.name] && routerName[routerObj.name] !== '' && routerName[routerObj.name]['isID'] && isGameShow) ? routerName[routerObj.name]['isID'] : '')
      childrenAttribute(routerObj.name)
      routerList.forEach(item => {
        if (routerArr[2] + 'p' === item.name) {
          item.children.push(routerChildren)
          isSame = false
        }
      })
      if (isSame) {
        router.children.push(routerChildren)
        routerList.push(router)
      }
      break
  }
})

2、router 配置文件

这个文件可以配置
左侧菜单中文名
左侧菜单图标
左侧菜单排序
左侧菜单权限
左侧菜单New!展示到期时间
动态id 可以配置任意参数

建议配置文件也按模块区分
routerName.js 写父菜单的配置
子菜单配置写在configurationModule中,该文件夹js文件会自动加载到routerName
有利于查看,有层次

routerName.js

// 自动获取modules配置
const files = require.context('./ConfigurationModule', false, /\.js$/)
let tmp
files.keys().forEach(key => {
  tmp = files(key).default
})
export const routerName = {
  ...tmp,
  /**
   * key 文件名
   * name 左侧菜单中文名
   * icon 左侧菜单图标
   * index 左侧菜单排序
   * permission 左侧菜单权限
   * newTime 左侧菜单New!展示到期时间
   * isID: 动态id 可以配置任意参数
   */
  system: {
    name: '系统管理',
    icon: 'form',
    index: 2,
    permission: [1, 2, 3],
    newTime: '2021-05-20',
  }
}

3、router生成菜单
router生成菜单关键是生成permission/state/routes 属性
addRoutes是动态路由属性

// 根据权限生成动态路由
generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRouterMap, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
 SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    // 如果isGameShow 设置true  控制选择游戏平台才能展示菜单选项
    if (isGameShow) {
      if (state.gameId !== '') {
        state.routes = constantRoutes.concat(routes)
      } else {
        state.routes = constantRoutes
      }
    } else {
      state.routes = constantRoutes.concat(routes)
    }
  },

4、菜单排序
菜单排序是在生成菜单路由的时候处理,利用sort 排序。filterAsyncRoutes本身就是一个递归方法,所以可在这里调用,处理树形结构的排序

// 左侧菜单排序
const compare = function(prop) {
  return function(obj1, obj2) {
    const val1 = obj1[prop]
    const val2 = obj2[prop]
    if (val1 < val2) {
      return -1
    } else if (val1 > val2) {
      return 1
    } else {
      return 0
    }
  }
}

在filterAsyncRoutes调用该方法

  routes = routes.sort(compare('index'))

注意:排序序号,父菜单只管父菜单兄弟之间的排序,子菜单只管子菜单兄弟之间的排序。所以这里会建议父菜单和子菜单的分开,子菜单配置按模块划分。

5、菜单New!标志
这里我处理的方式是在配置文件中配置newTime,传入时间字符串,比如’2021-05-20‘,这个时间与当前系统时间对比,如果时间未到就展示,过了隐藏。

 if (title) {
      if (newTime && newTime.getTime() > new Date().getTime()) {
        vnodes.push(<span slot='title'>{(title)}<span style='color: red;display: inline-block;margin-top: -10px;padding:0 5px;'>New!</span></span>)
      } else {
        vnodes.push(<span slot='title'>{(title)}</span>)
      }
    }

注意:1、时间要字符串标准格式(2021-05-20),匹配时间是在该时间的0点,而非24点。
2、子菜单配置的newTime,父菜单也需要配置,并且要等于子菜单中最大的newTime。这样才能保持一致。(这里其实可以让父菜单根据子菜单的配置来自动完成,目前支持手动配置)。
3、权限配置也类似。

6、配置 isID、动态id 可以配置任意参数
动态isID只能配置在子路由中,父路由是不生效的。配置的参数格式必须是’/:‘+任意字符串。意思就是传的参数不局限于id,可任意。

// 如果有gameId 处理/:id 动态路由 可以配置任意参数
      if (store.state.permission.gameId !== '' && (routerName[to.name] && routerName[to.name] !== '' && to.path.indexOf(routerName[to.name]['isID']) > -1) && store.state.settings.isGameShow) {
        const params = {}
        const isID = routerName[to.name]['isID'].substring(2, routerName[to.name]['isID'].length)
        params[isID] = store.state.permission.gameId
        next({ ...to, params: params })
      }

注意:如果使用动态路由,在路由拦截的地方进行跳转传参,那在左侧菜单的时候就不能使用path来做唯一值,这样选中效果就不生效。可以使用name来做唯一值

7、异步请求路由配置

// 映射服务器返回菜单与本地component
function generateAsyncRouter(serverRouterMap, children = false) {
  return serverRouterMap.map(item => {
    const isParent = item.children && item.children.length > 0
    const parent = generateRouter(item, isParent, children)
    if (isParent) {
      parent.children = generateAsyncRouter(item.children, true)
    }
    return parent
  })
}
const generateRouter = (item, isParent, children) => ({
  path: isParent ? `/${item.url}` : item.url || '',
  name: isParent ? 'p' + item.url : item.url || '',
  alwaysShow: false,
  meta: { title: item.menuName, icon: item.icon, id: item.menuID, newTime: item.newTime ? new Date(item.newTime) : new Date(), noCache: false },
  component: isParent && !children ? routerMaps['Layout'] : routerMaps[item.url]
})

接口返回的数据格式

'data': [{
    'menuID': '10000000',
    'menuName': '系统管理',
    'icon': 'form',
    'url': 'system',
    'newTime': '2021-05-30',
    'children': [
      {
        'menuID': '10001000',
        'menuName': '用户管理',
        'icon': 'form',
        'url': 'user/:id',
        'children': null,
        'newTime': '2021-05-30'
      },
      {
        'menuID': '10002000',
        'menuName': '菜单管理',
        'icon': 'form',
        'url': 'menu',
        'children': null
      }
    ]
  }]

对应配置的router文件路径

// 处理接口请求的router
export const routerMaps = {
  Layout: () => import('@/layout/index'),
  ...routerMap
}

 // 处理接口请求返回router情况
      routerMap[routerObj.name] = routerObj.component

请求生成路由

 // 异步获取侧边栏数据
        getPageMenu({}).then(res => {
          console.log(res)
          if (res && res.code.toString() === '200') {
            const data = res.data != null ? res.data : []
            accessedRoutes = generateAsyncRouter(data).concat(filterAsyncRoutes(ApiRouterMap, roles))
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
          }
        })

注意:异步请求路由,权限,排序都由后台完成。请求接口得到的数据就是已经经过权限过滤,排序之后的数据。如果是异步请求路由,则无需在配置routerName文件。这个相对本地配置router来说是简单的,后台替我们分担了一部分工作。

6、store

store内存存储数据,可以复用,避免重复调用接口。这个并不是将所有接口都写在store里面就越好,只需储存一些数据不需要实时变动的。文件多可做个按需加载,一般在大型项目中需要。目前我没有写。

按需加载文件

var ffVuex = {
  install: function(vue) {
    vue.mixin({
      beforeCreate: function() {
        if (this.$options.isVuex) {
          var name = this.$options.name;
          let moduleObj = this.$store._modules.root._children;
          let onOff = true;
          Object.keys(moduleObj).forEach(function(key) {
            if (key === name) {
              onOff = false;
            }
          });
          if (onOff) {
            let res = require("../store/module/" + name);
            this.$store.registerModule(this.$options.name, res.default);
          }
        }
      },
    });
  },
};
module.exports = ffVuex;

mian.js中去引入即可
注意:1、视图中的定义name与store/modules下的文件名一直
2、定义是否需要vuex( isVuex:true)

7、utils

公共的方法写在utils/index.js中
Reg 表单校验
auth 本地存储数据

8、微前端配置

之前写过微前端配置

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容