基于vue-admin-template二次开发
1、添加路由 新增页面组件
// 静态路由
export const constantRoutes = [
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true
},
{
path: '/',
component: Layout,
redirect: '/appointment/index'
},
{
path: '/appointment',
component: Layout,
children: [
{
path: 'index',
name: 'appointment',
component: () => import('@/views/appointment/index'),
meta: { title: '预约中心', icon: 'form' }
}
]
}
]
// 动态路由
export const asyncRouterMap = [
{
path: '/manage',
component: Layout,
name: 'manage',
meta: { title: '管理中心', icon: 'el-icon-s-help', breadcrumb: false, role: ['admin', 'teacher'] },
children: [
{
path: 'appointmentManage',
name: 'appointmentManage',
component: () => import('@/views/management/appointmentManage/index'),
meta: { title: '预约管理', icon: 'el-icon-s-order', role: ['admin', 'teacher'] }
},
{
path: 'userManage',
name: 'userManage',
component: () => import('@/views/management/userManagement/index'),
meta: { title: '用户管理', icon: 'el-icon-user-solid', role: ['admin', 'teacher'] }
},
{
path: 'roomManage',
name: 'roomManage',
component: () => import('@/views/management/roomManagement/index'),
meta: { title: '实验室管理', icon: 'el-icon-s-home', role: ['admin', 'teacher'] }
}
]
},
// 404 page must be placed at the end !!!
{
path: '/404',
component: () => import('@/views/404'),
hidden: true
},
{ path: '*', redirect: '/404', hidden: true }]
2、规范创建组件和接口文件
3、api中存后端接口,组件中调用api
export function login(data) {
return request({
url: '/user/login',
method: 'post',
data
})
}
4、修改request.js
// 从vuex中拿token
if (store.getters.token) {
// let each request carry token
// ['X-Token'] is a custom headers key
// please modify it according to the actual situation
config.headers['tokenName'] = getToken()
}
// if the custom code is not 200, it is judged as an error. 根据后端返回的code修改
if (res.code !== 200) {
Message({
message: res.msg || 'Error',
type: 'error',
duration: 5 * 1000
})
5、根据自己的需要修改store
const getters = {
sidebar: state => state.app.sidebar,
device: state => state.app.device,
token: state => state.user.token,
name: state => state.user.name,
userId: state => state.user.userId,
studentId: state => state.user.studentId,
college: state => state.user.college,
major: state => state.user.major,
routers: state => state.permission.routers,
addRouters: state => state.permission.addRouters
}
export default getters
// store/permission.js
import { asyncRouterMap, constantRoutes } from '@/router'
function hasPermission(roles, route) {
if (route.meta && route.meta.role) {
return roles.some(role => route.meta.role.indexOf(role) >= 0)
} else {
return true
}
}
const state = {
routers: constantRoutes,
addRouters: []
}
const mutations = {
SET_ROUTERS: (state, routers) => {
state.addRouters = routers
state.routers = constantRoutes.concat(routers)
}
}
const actions = {
GenerateRoutes({ commit }, data) {
return new Promise(resolve => {
const roles = data
const accessedRouters = asyncRouterMap.filter(v => {
if (roles.indexOf('admin') >= 0) return true
if (hasPermission(roles, v)) {
if (v.children && v.children.length > 0) {
v.children = v.children.filter(child => {
if (hasPermission(roles, child)) {
return child
}
return false
})
return v
} else {
return v
}
}
return false
})
commit('SET_ROUTERS', accessedRouters)
resolve()
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
6、动态菜单和路由
// src/permission.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'] // 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()
} else {
const hasGetUserInfo = store.getters.name
if (hasGetUserInfo) {
next()
} else {
try {
// get user info
await store.dispatch('user/getInfo').then(res => {
// 根据权限动态生成路由
const { roles } = res
store.dispatch('permission/GenerateRoutes', roles).then(() => {
router.addRoutes(store.getters.addRouters) // 根据roles动态添加可访问路由表
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
})
})
next()
} 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()
})
// src/layout/components/Sidebar/index.vue
computed: {
...mapGetters([
'sidebar',
'routers'
])}
<sidebar-item v-for="route in routers" :key="route.path" :item="route" :base-path="route.path" />
7、跨域
dev下跨域
# just a flag
ENV = 'development'
# base api
VUE_APP_BASE_API = '/api'
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
proxy: {
'/api': {
// 这里就改成本地的接口路径
target: 'http://localhost:8081',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
// before: require('./mock/mock-server.js')
}
prod下的跨域
使用nginx反向代理
server
{
listen 8088; # nginx监听的端口
server_name yuyue;
location / {
root /home/william/yuyue_server/dist/; # 托管dist文件夹
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://1.1.1.1:8081/; # 后端服务器的地址 注意结尾的 /
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
# just a flag
ENV = 'production'
# base api nginx的地址和服务的监听端口
VUE_APP_BASE_API = 'http://1.1.1.1:8088/api'
ge 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
```ini
# just a flag
ENV = 'production'
# base api nginx的地址和服务的监听端口
VUE_APP_BASE_API = 'http://1.1.1.1:8088/api'