第一步,
下载模板:地址:https://panjiachen.gitee.io/vue-element-admin-site/zh/guide/
vue-admin-template和vue-element-admin是两个东西,vueadmin-template是基础模板,
适合二次开发,vue-element-admin是后台集成方案!!
第二步:
可以把src/router/index里面多余的路由删除,只留login,404,和默认的( '/ '),*路由也删除了,
后边说具体为什么,然后把src/views/下边留下login目录和dashboard目录就行了,是目录,别
删错了,
第三步:
修改接口,找到根目录下边的.env.development,第六行代码修改成后端接口,例:VUE_APP_BASE_API = ‘http://localhost:3000’
第四步:
在src/api/user下新增路由接口,照着上面的,比葫芦画瓢,直接ctrl+c,ctrl+v:
import request from '@/utils/request'
import { getToken } from '@/utils/auth'
// 登录
export function login(data) {
return request({
url: '/login',
method: 'post',
data
})
}
// 获取用户信息
export function getInfo(token) {
return request({
url: '/userInfo',
method: 'get',
params: { token }
})
}
// 退出
export function logout() {
return request({
url: '/logout',
method: 'post'
})
}
export function getRouters() {
return request({
url: '/getRouters?username=' + getToken(),
method: 'get'
})
}
url地址记得改,还有上面的login,getinfo,记得改成自己写的后端对应接口,
第五步:
打开utils下的request文件,看第49行代码,如果后端返回的code只要不是2000,都进不去,
后端响应的时候记得加上,不想是20000也可自行修改,
第六步:
src/store/modules下新增permission.js文件,复制以下内容,
import { constantRoutes } from '@/router'
import { getRouters } from '@/api/user'
import Layout from '@/layout/index'
const permission = {
state: {
routes: [],
addRoutes: []
},
mutations: {
SET_ROUTES: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes.concat(routes)
}
},
actions: {
GenerateRoutes({ commit }) {
return new Promise(resolve => {
getRouters().then(res => {
const accessedRoutes = filterAsyncRouter(res.data)
accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
commit('SET_ROUTES', accessedRoutes)
console.log(accessedRoutes)
resolve(accessedRoutes)
})
})
}
}
}
function filterAsyncRouter(asyncRouterMap) {
return asyncRouterMap.filter(route => {
if (route.component) {
if (route.component === 'Layout') {
route.component = Layout
} else {
route.component = loadView(route.component)
}
}
if (route.children != null && route.children && route.children.length) {
route.children = filterAsyncRouter(route.children)
}
return true
})
}
const loadView = (view) => {
return (resolve) => require([`@/views/${view}`], resolve)
}
export default permission
然后打开src/store/getters文件,加入:
permission_routes: state => state.permission.routes
打开src/store/index文件,上面引入:import permission from './modules/permission'
下边的modules里面加入permission
,
第七步:
src/permission.js 33的try里面,加入
const accessRoutes = await store.dispatch('GenerateRoutes')
router.addRoutes(accessRoutes)
next({ ...to, replace: true })
//把另一个next()删了把
第八步:
修改src/views/login下的登录页面,直接复制,粘贴:
<template>
<div class="login-container">
<el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
<div class="title-container">
<h3 class="title">Login Form</h3>
</div>
<el-form-item prop="username">
<span class="svg-container">
<svg-icon icon-class="user" />
</span>
<el-input
ref="username"
v-model="loginForm.username"
placeholder="Username"
name="username"
type="text"
tabindex="1"
auto-complete="on"
/>
</el-form-item>
<el-form-item prop="password">
<span class="svg-container">
<svg-icon icon-class="password" />
</span>
<el-input
:key="passwordType"
ref="password"
v-model="loginForm.password"
:type="passwordType"
placeholder="Password"
name="password"
tabindex="2"
auto-complete="on"
@keyup.enter.native="handleLogin"
/>
<span class="show-pwd" @click="showPwd">
<svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
</span>
</el-form-item>
<el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">Login</el-button>
<div class="tips">
<span style="margin-right:20px;">username: admin</span>
<span> password: any</span>
</div>
</el-form>
</div>
</template>
<script>
// 引入正则
// import { validUsername } from '@/utils/validate'
export default {
name: 'Login',
data() {
const validateUsername = (rule, value, callback) => {
if (value === '') {
callback(new Error('用户名不能为空'))
} else {
callback()
}
}
const validatePassword = (rule, value, callback) => {
if (value === '') {
callback(new Error('密码不能为空'))
} else {
callback()
}
}
return {
loginForm: {
username: '',
password: ''
},
loginRules: {
username: [{ required: true, trigger: 'blur', validator: validateUsername }],
password: [{ required: true, trigger: 'blur', validator: validatePassword }]
},
loading: false,
passwordType: 'password',
redirect: undefined
}
},
watch: {
$route: {
handler: function(route) {
this.redirect = route.query && route.query.redirect
},
immediate: true
}
},
methods: {
showPwd() {
if (this.passwordType === 'password') {
this.passwordType = ''
} else {
this.passwordType = 'password'
}
this.$nextTick(() => {
this.$refs.password.focus()
})
},
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
}
})
}
}
}
</script>
<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$bg:#283443;
$light_gray:#fff;
$cursor: #fff;
@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
.login-container .el-input input {
color: $cursor;
}
}
/* reset element-ui css */
.login-container {
.el-input {
display: inline-block;
height: 47px;
width: 85%;
input {
background: transparent;
border: 0px;
-webkit-appearance: none;
border-radius: 0px;
padding: 12px 5px 12px 15px;
color: $light_gray;
height: 47px;
caret-color: $cursor;
&:-webkit-autofill {
box-shadow: 0 0 0px 1000px $bg inset !important;
-webkit-text-fill-color: $cursor !important;
}
}
}
.el-form-item {
border: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(0, 0, 0, 0.1);
border-radius: 5px;
color: #454545;
}
}
</style>
<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;
.login-container {
min-height: 100%;
width: 100%;
background-color: $bg;
overflow: hidden;
.login-form {
position: relative;
width: 520px;
max-width: 100%;
padding: 160px 35px 0;
margin: 0 auto;
overflow: hidden;
}
.tips {
font-size: 14px;
color: #fff;
margin-bottom: 10px;
span {
&:first-of-type {
margin-right: 16px;
}
}
}
.svg-container {
padding: 6px 5px 6px 15px;
color: $dark_gray;
vertical-align: middle;
width: 30px;
display: inline-block;
}
.title-container {
position: relative;
.title {
font-size: 26px;
color: $light_gray;
margin: 0px auto 40px auto;
text-align: center;
font-weight: bold;
}
}
.show-pwd {
position: absolute;
right: 10px;
top: 7px;
font-size: 16px;
color: $dark_gray;
cursor: pointer;
user-select: none;
}
}
</style>
修改src/layout/components/slider/index文件,第15行的routes,换成permission_routes
,
如:
...mapGetters([
'sidebar',
'permission_routes'
]),
mapGetters里面新增,'permission_routes'
最后一步,看一下我node模拟的路由信息,data是个关键字,
const express = require('express');
const cors = require('cors');
const body_parser = require('body-parser');
const app = express();
app.use(cors());
app.use(body_parser.json());
app.use(body_parser.urlencoded({extended: false}));
// 登录,返回token
app.post('/login',(req,res) => {
res.json({"code":200,"data":{"token": req.body.username}})
});
// 获取用户信息,返回用户信息
app.get('/userInfo', (req,res) => {
res.json({"code":200,"data":{name: req.query.token}})
});
app.post('/logout', (req,res) => {
});
app.get('/getRouters', (req,res) => {
if(req.query.username === 'admin'){
res.json({"code":200,'data': [
{
path: '/first',
component: 'Layout',
children: [
{
path: 'dashboard',
name: 'first',
component: 'demo/first',
meta: {
title: '第一个',
icon: 'dashboard'
}
}
]
},
{
path: '/second',
component: 'Layout',
children: [
{
path: 'dashboard',
name: 'second',
component: 'demo/second',
meta: {
title: '第二个',
icon: 'dashboard'
}
}
]
}
]})
} else {
res.json({"code":200,'data': [
{
path: '/first',
component: 'Layout',
children: [
{
path: 'dashboard',
name: 'first',
component: 'demo/first',
meta: {
title: '第一个',
icon: 'dashboard'
}
}
]
}
]})
}
})
app.listen(3000, () => {
console.log('port 3000 is listening');
})
说一下为什么删除 * 路由,因为addRouter路由的时候,具体没看过,我大概猜想是因为添加的时候想push方法,那么如果不删除,就会导致 * 不是在路由的最后,会引起bug,应该是这样,具体各位可以查一下,大概思路应该这样,本人也是刚入门,大神轻喷!!!
中文element-ui,main里面第七行代码最后的en换成zh-CN就可以,记得新增页面,
新增页面的时候提示的话,就直接add,就可以了,要不组件会变红,可自查相关内容,控制台:npm run lint – --fix,修复错误,