以下仅作为自己个人学习使用
前言:
需要后端的接口已经在另外一篇博客写了,需要的小伙伴们可以去那边参考,下面是链接
https://www.cnblogs.com/Amyel/p/17233060.html
正片:
- 安装npm install axios -S
npm install axios -S
- 封装request
import axios from 'axios'
const request = axios.create({
baseURL: 'http://localhost:9090', // 注意!! 这里是全局统一加上了 '/api' 前缀,也就是说所有接口都会加上'/api'前缀在,页面里面写接口的时候就不要加 '/api'了,否则会出现2个'/api',类似 '/api/api/user'这样的报错,切记!!!
timeout: 5000
})
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
// config.headers['token'] = user.token; // 设置请求头
return config
}, error => {
return Promise.reject(error)
});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response => {
let res = response.data;
// 如果是返回的文件
if (response.config.responseType === 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default request
- vue.config.js配置:
// 跨域配置
module.exports = {
devServer: { //记住,别写错了devServer//设置本地默认端口 选填
port: 8080,
proxy: { //设置代理,必须填
'/api': { //设置拦截器 拦截器格式 斜杠+拦截器名字,名字可以自己定
target: 'http://localhost:8080', //代理的目标地址
changeOrigin: true, //是否设置同源,输入是的
pathRewrite: { //路径重写
'^/api': '' //选择忽略拦截器里面的内容
}
}
}
}
}
- 在main.js里面全局使用
import request from './utils/request';
Vue.prototype.request = request
- 使用
<template>
<div>
<el-container style="height:100vh; border: 1px solid #eee">
<!-- 侧边栏 -->
<el-aside :width="width" style="background-color: rgb(238, 241, 246);">
<el-menu :collapse="isCollapse" default-active="1" class="el-menu-vertical-demo" style="min-height: 100%;" background-color="rgb(48,64,86)" text-color="#fff" active-text-color="#409EFF">
<div style="height:60px;line-height:60px;text-align: center;">
<img src="../../assets/logo.png" alt="" style="width:20px;position: relative;top:5px;">
<b style="color:#fff;margin-left: 5px;" v-show="isshow">后台管理系统</b>
</div>
<el-menu-item index="1">
<template>
<i class="el-icon-location"></i>
<span slot="title">首页</span>
</template>
</el-menu-item>
<el-menu-item index="2">
<i class="el-icon-menu"></i>
<span slot="title">用户管理</span>
</el-menu-item>
<el-menu-item index="3">
<i class="el-icon-document"></i>
<span slot="title">权限管理</span>
</el-menu-item>
<el-menu-item index="4">
<i class="el-icon-setting"></i>
<span slot="title">系统管理</span>
</el-menu-item>
</el-menu>
</el-aside>
<el-container>
<!-- 头部 -->
<el-header style="text-align: right; font-size: 12px">
<span @click="Collapse" style="float: left;font-size:20px; cursor: pointer;"><i :class="icon"></i></span>
<div>
<el-breadcrumb separator="/">
<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
<el-breadcrumb-item><a href="/user">用户管理</a></el-breadcrumb-item>
</el-breadcrumb>
</div>
<el-dropdown>
<i class="el-icon-arrow-down" style="margin-right: 15px;font-size:20px; cursor: pointer;"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>个人信息</el-dropdown-item>
<el-dropdown-item>退出</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<span style="font-size:16px;">张三</span>
</el-header>
<!-- 内容主题部分 -->
<el-main>
<div style="margin:10px 5px; ">
<el-input style="width:200px;margin-right: 5px;" suffix-icon="el-icon-search" v-model="username" placeholder="请输入名称"></el-input>
<el-input style="width:200px;margin-right: 5px;" suffix-icon="el-icon-message" v-model="email" placeholder="请输入邮箱"></el-input>
<el-input style="width:200px;margin-right: 5px;" suffix-icon="el-icon-message" v-model="address" placeholder="请输入地址"></el-input>
<el-button type="primary" @click="load">搜索</el-button>
<el-button type="warning" @click="reset">重置</el-button>
</div>
<div style="margin:20px 5px; ">
<el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
<el-button type="danger" @click="delbatch">批量删除 <i class="el-icon-remove-outline"></i></el-button>
<el-button type="primary">导入 <i class="el-icon-plus"></i></el-button>
<el-button type="primary">导出 <i class="el-icon-minus"></i></el-button>
</div>
<el-table border :data="tableData" :header-cell-style="{background:'#eef1f6',color:'#606266'}" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55">
</el-table-column>
<el-table-column prop="id" label="ID" width="80" align="center">
</el-table-column>
<el-table-column prop="username" label="用户名" width="180" align="center">
</el-table-column>
<el-table-column prop="nickname" label="昵称" width="180" align="center">
</el-table-column>
<el-table-column prop="email" label="邮箱" width="180" align="center">
</el-table-column>
<el-table-column prop="phone" label="电话" width="180" align="center">
</el-table-column>
<el-table-column prop="address" label="地址" align="center">
</el-table-column>
<el-table-column label="操作" align="center" width="200">
<template slot-scope="scope">
<el-button @click="handleEdit(scope.row)" type="success" size="mini"><i class="el-icon-edit"></i> 编辑</el-button>
<el-button @click="del(scope.row.id)" type="danger" size="mini"><i class="el-icon-delete"></i> 删除</el-button>
</template>
</el-table-column>
</el-table>
<div style="padding-top: 20px;">
<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
</el-pagination>
</div>
<el-dialog :title="title" :visible.sync="dialogFormVisible" center width="30%">
<el-form :rules="rules" ref="form" :model="form" size="small">
<el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
<el-input v-model="form.username" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="昵称" :label-width="formLabelWidth" prop="nickname">
<el-input v-model="form.nickname" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
<el-input v-model="form.email" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
<el-input v-model="form.phone" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="地址" :label-width="formLabelWidth" prop="address">
<el-input v-model="form.address" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</div>
</el-dialog>
</el-main>
</el-container>
</el-container>
</div>
</template>
<script>
export default {
name: 'home',
data () {
//自定义的邮箱和手机验证规则
let checkEmail = (rule, value, callback) => {//验证邮箱
const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
if (this.form.email != '' && !regEmail.test(this.form.email)) {
callback(new Error('请输入有效的邮箱'));
}
}
return {
tableData: [],
total: 0,
pageNum: 1,
pageSize: 5,
isCollapse: false,
width: '200px',
icon: 'el-icon-s-fold',
isshow: true,
input: '',
username: '',
email: '',
address: '',
dialogFormVisible: false,
formLabelWidth: '80px',
title: '新增用户',
multipleSelection: [],//批量删除
form: {
username: '',
nickname: '',
email: '',
phone: '',
address: ''
},
rules: {
username: [
{ required: true, message: '请输入账户名', trigger: 'blur' },
{ min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
],
nickname: [
{ required: true, message: '请输入昵称', trigger: 'blur' },
],
email: [
{ required: true, message: '请输入邮箱', trigger: 'blur' },
{ validator: checkEmail, trigger: "blur" }
],
phone: [
{ required: true, message: '请输入手机号', trigger: 'blur' },
{ min: 11, max: 11, message: '请输入11位数的手机号码', trigger: 'blur' },
{ pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'blur' }
],
address: [
{ required: true, message: '请输入地址', trigger: 'blur' },
]
}
}
},
created () {
this.load()
},
methods: {
//查询数据
load () {
this.request.get("/user/page", {
params: {
pageNum: this.pageNum,
pageSize: this.pageSize,
total: this.total,
username: this.username,
email: this.email,
address: this.address
}
}).then(res => {
this.tableData = res.records
this.total = res.total
})
},
//新增
//还没有加上效验,可以自己去element-ui官网查看怎么加上表格效验
//https://element.eleme.cn/#/zh-CN
save () {
this.request.post("/user/save", this.form).then(res => {
if (res) {
this.$message.success("保存成功")
this.dialogFormVisible = false
this.load()
} else {
this.$message.error("保存失败")
}
})
},
//编辑
handleEdit (row) {
this.form = row
this.dialogFormVisible = true
this.title = '编辑用户'
},
//删除
del (id) {
this.request.delete("/user/" + id).then(res => {
this.$confirm('确认删除此用户嘛, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
if (res) {
this.$message.success("删除成功")
this.load()
} else {
this.$message.error("删除失败")
}
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
})
},
//批量删除
handleSelectionChange (val) {
console.log(val);
this.multipleSelection = val;
},
//点击批量删除的时候
delbatch () {
let ids = this.multipleSelection.map(r => r.id) // [{},{},{}]把对象数组变成纯ID数组 [1,2,3]
this.request.post("/user/del/batch", ids).then(res => {
this.$confirm('你确定批量删除这些数据嘛, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
if (res) {
this.$message.success("批量删除成功")
this.load()
} else {
this.$message.error("批量删除失败")
}
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
})
},
//点击之后打开弹窗
handleAdd () {
this.dialogFormVisible = true
//清空表单
this.form = {}
},
Collapse () {
if (this.isCollapse != false) {
this.isCollapse = false
this.width = "200px"
this.icon = 'el-icon-s-fold'
this.isshow = true
} else {
this.isCollapse = true
this.width = "64px"
this.icon = 'el-icon-s-unfold'
this.isshow = false
}
},
handleSizeChange (val) {
this.pageSize = val
this.load()
},
handleCurrentChange (val) {
this.pageNum = val
this.load()
},
//重置
reset () {
this.username = ''
this.email = ''
this.address = ''
this.load()
}
},
};
</script>
<style lang="less" scoped>
.el-header {
position: relative;
background-color: #fff;
color: #333;
line-height: 60px;
border-bottom: 2px solid #eee;
}
.el-aside {
color: #333;
transition: width 0.25s;
-webkit-transition: width 0.25s;
-moz-transition: width 0.25s;
-webkit-transition: width 0.25s;
-o-transition: width 0.25s;
}
/*加快侧边栏文字消失的速度*/
.el-menu {
transition: all 60ms;
}
.el-menu-item:hover {
background-color: rgb(48, 64, 110) !important;
border-radius: 10px;
}
.el-breadcrumb {
position: absolute;
top: 23px;
left: 50px;
}
</style>
- 效果图