文章目录
前言
本次内容项目基于Vue3.0创建;
利用express读取MySQL数据库,通过element-ui展示内容。
一、初始化vue项目
1.安装vue和vue-cli
2.初始化vue项目
vue create test2
二、安装依赖
1.package.json中添加依赖
"dependencies": {
"axios": "^0.24.0",
"element-ui": "^2.15.6",
"express": "^4.17.1",
"mysql": "^2.18.1",
}
2.安装
npm install
3.main.js中引入依赖
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
Vue.prototype.$http = window.axios
Vue.use(ElementUI)
三、配置页面接口
1.components中创建db.vue
<template>
<div>
<div class="top">
<el-input v-model="tableDataName" placeholder="请输入姓名" style="width: 240px"></el-input>
<el-button type="primary" @click="doFilter">搜索</el-button>
<el-button @click="doReset">重置</el-button>
<div class="space">
<el-table :data="tableDataEnd" border style="width: 100%">
<el-table-column prop="id" sortable label="序号" width="180" header-align="center" align="center">
</el-table-column>
<el-table-column prop="userName" sortable label="用户名" width="180" header-align="center" align="center">
</el-table-column>
<el-table-column prop="password" sortable label="密码" header-align="center" align="center">
</el-table-column>
<el-table-column prop="tel" sortable label="电话" header-align="center" align="center">
</el-table-column>
<el-table-column label="操作" header-align="center" align="center">
<template slot-scope="scope">
<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button size="small" type="danger" @click="deleteRow(scope.row.id)">删除</el-button>
</template>
</el-table-column>
</el-table>
<div class="space">
<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
:page-sizes="[1, 2, 3, 4]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
:total="totalItems">
</el-pagination>
</div>
<el-dialog title="用户信息" :visible.sync="dialogFormVisible">
<el-form :model="form">
<el-form-item label="id" :label-width="formLabelWidth">
<el-input v-model="form.id" disabled auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="用户名" :label-width="formLabelWidth">
<el-input v-model="form.userName" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="密码" :label-width="formLabelWidth">
<el-input v-model="form.password" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="电话" :label-width="formLabelWidth">
<el-input v-model="form.tel" auto-complete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="cancel">取 消</el-button>
<el-button type="primary" @click="update">确 定</el-button>
</div>
</el-dialog>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
data()
{
return {
dialogFormVisible: false,
formLabelWidth: "80px",
dialogVisible: false,
dialogVisible1: false,
form: {},
tableDataBegin: [],
tableDataName: "",
tableDataEnd: [],
currentPage: 1,
pageSize: 4,
totalItems: 10,
filterTableDataEnd: [],
flag: false,
};
},
handleSelectionChange(val)
{
this.users.id = val;
console.log("选中的数据集合为:", val);
},
created() { },
mounted()
{
this.querry();
},
computed: {
// 测试代码
username()
{
let username = sessionStorage.getItem("ms_username");
console.log(username);
if (username !== "test") {
alert("11");
}
return username ? username : this.name;
},
},
methods: {
querry()
{
axios.get("/api/user/list").then((res) =>
{
console.log(res);
this.tableDataBegin = res.data;
console.log(this.tableDataEnd);
this.totalItems = this.tableDataBegin.length;
if (this.totalItems > this.pageSize) {
for (let index = 0; index < this.pageSize; index++) {
this.tableDataEnd.push(this.tableDataBegin[index]);
}
} else {
this.tableDataEnd = this.tableDataBegin;
}
});
},
add()
{
this.form = {
id: "",
userName: "",
password: "",
address: "",
};
this.dialogFormVisible = true;
},
update()
{
console.log(this.form.id);
console.log(this.form.userName);
console.log(this.form.password);
console.log(this.form.tel);
var that = this;
axios
.post("/api/user/up", {
id: this.bookid,
password: this.form.password,
tel: this.form.tel,
userName: this.form.userName,
})
.then(function (res)
{
console.log(res.data);
if (res.data.state == 0) {
const loading = that.$loading({
lock: true,
text: "修改成功",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.7)",
});
setTimeout(() =>
{
loading.close();
}, 1500);
}
})
.catch(function (err)
{
console.log(err);
});
this.dialogFormVisible = false;
},
handleEdit(index, row)
{
this.form = this.tableDataEnd[index];
this.currentIndex = index;
this.dialogFormVisible = true;
},
handleDelete(index, row)
{
this.$confirm("永久删除该文件, 是否继续?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(() =>
{
// 移除对应索引位置的数据,可以对row进行设置向后台请求删除数据
this.tableDataEnd.splice(index, 1);
this.$message({
type: "success",
message: "删除成功!",
});
})
.catch(() =>
{
this.$message({
type: "info",
message: "已取消删除",
});
});
},
load()
{
var loading = this.$loading({
lock: true,
text: "等待跳转",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.7)",
});
// 在注册界面停留两秒钟跳转登录界
setTimeout(() =>
{
loading.close();
this.querry();
// res.end()
}, 3000);
},
deleteRow(bookid)
{
console.log(bookid);
if (confirm("确定要删除吗") == true) {
var that = this;
//网络请求获取数据axios,根据id来删除户。id传参到后端。
axios
.post("/api/user/del", {
id: bookid,
})
.then((res) =>
{
this.doReset();
console.log(res.data);
})
.catch(function (err)
{
//请求失败
console.log("失败了" + err);
});
}
},
cancel()
{
// 取消的时候直接设置对话框不可见即可
this.dialogFormVisible = false;
},
doReset()
{
this.tableDataEnd = [];
this.tableDataName = "";
this.filterTableDataEnd = [];
this.tableDataBegin.forEach((value, index) =>
{
if (value.userName) {
if (value.userName.indexOf(this.tableDataName) >= 0) {
this.filterTableDataEnd.push(value);
}
}
});
this.tableDataName = "";
this.currentPage = 1;
this.totalItems = this.filterTableDataEnd.length;
this.querry();
},
doFilter()
{
if (this.tableDataName == "") {
this.$message.warning("查询条件不能为空!");
this.tableDataName = "";
return;
}
this.tableDataEnd = [];
this.filterTableDataEnd = [];
this.tableDataBegin.forEach((value, index) =>
{
if (value.userName) {
if (value.userName.indexOf(this.tableDataName) >= 0) {
this.filterTableDataEnd.push(value);
}
}
});
this.tableDataName = "";
this.currentPage = 1;
this.totalItems = this.filterTableDataEnd.length;
//渲染表格,根据值
this.currentChangePage(this.filterTableDataEnd);
this.flag = true;
},
//每页展示条数
handleSizeChange(val)
{
console.log(`每页 ${val} 条`);
this.pageSize = val;
this.handleCurrentChange(1);
},
handleCurrentChange(val)
{
console.log(`当前页: ${val}`);
this.currentPage = val;
//需要判断是否检索
if (!this.flag) {
this.currentChangePage(this.tableDataBegin);
console.log(this.tableDataEnd);
} else {
this.currentChangePage(this.filterTableDataEnd);
console.log(this.tableDataEnd);
}
}, //组件自带监控当前页码
//点击下一页
currentChangePage(list)
{
let from = (this.currentPage - 1) * this.pageSize;
let to = this.currentPage * this.pageSize;
this.tableDataEnd = [];
for (; from < to; from++) {
if (list[from]) {
this.tableDataEnd.push(list[from]);
}
}
},
},
};
</script>
<style scoped>
.space {
margin-top: 30px;
}
.top {
position: absolute;
left: 50%;
top: 50%;
width: 90%;
height: 430px;
margin: -260px 0 0 -520px;
}
</style>
>
2.编写后端接口和数据库配置
1.src下创建server文件夹,创建utils文件夹,创建数据库连接助手:
// 数据库连接助手
const mysql = require('mysql');
class DBHelper{
getConn(){
let conn = mysql.createConnection({
// 数据库连接配置
host: '', // 新建数据库连接时的 主机名或ID地址 内容
user: '',
database: '', // 数据库名
password: '', // root 密码
port: '',
// 设置以字符换的形式展示。不会出现时区少8小时问题。
dateStrings:true
});
conn.connect();
return conn;
}
}
module.exports = DBHelper;
2.创建api文件夹,创建userApi.js
const express = require('express');
const router = express.Router();
const DBHelper = require('../utils/DBHelper');
const sql = require('../sqlMap');
// 查询用户
router.get('/list', (req, res) => {
let sqlStr = sql.user.list;
let conn = new DBHelper().getConn();
conn.query(sqlStr,(err, result) => {
if (err) {
res.json(err);
} else {
console.log(result);
res.json(result)
}
});
});
// 删除用户接口
router.post('/del', (req, res) => {
let sqlStr = sql.user.del;
let params = req.body;
let conn = new DBHelper().getConn();
conn.query(sqlStr, [params.id], (err, result) => {
let state = {}
if (result.length > 0) {
state.state = 1;
res.json(state);
} else {
state.state = 0;
res.json(state);
}
});
conn.end();
});
// 更新用户信息,修改用户信息
router.post('/up', (req, res) => {
let sqlStr = sql.user.update2;
let params = req.body;
let conn = new DBHelper().getConn();
conn.query(sqlStr, [params.password,params.tel,params.userName,], (err, result) => {
let state = {}
if (result.length > 0) {
state.state = 1;
res.json(state);
} else {
state.state = 0;
res.json(state);
}
});
conn.end();
});
module.exports = router;
3.创建index.js
const http = require('http');
const badyParser = require('body-parser');
const express = require('express');
const userApi = require('./api/userApi');
const DBHelper = require('./utils/DBHelper');
let conn = new DBHelper().getConn();
let app = express();
let server = http.createServer(app);
app.use(badyParser.json());
app.use(badyParser.urlencoded({
extended: false
}));
app.use('/api/user', userApi);
server.listen(3000, () => {
console.log(' success!! port:3000')
})
4.创建sqlMap.js
// sql语句,在Api中调用
var sqlMap = {
user: {
add: 'insert ignore into user(userName, password,tel) values (? , ? , ?)',
// 删除用户
del: 'delete from user where id = ? ',
// 查询用户
valid: 'select * from user where userName = ? and password = ? ',
valid2: 'select * from user where userName = ? ',
// 更新用户信息
update: 'update user set password= ? where userName= ? ',
update2: 'update user set password=?,tel=? where userName=? ',
// 查询环境数据
list: 'select * from user ',
}
};
module.exports = sqlMap;
5.server目录结构
6.数据库表结构
四、配置页面路径
1.修改APP.vue默认页面
import db from './components/db.vue'
export default {
name: 'app',
components: {
db
}
}
2.解决跨域问题
1.在项目的根目录新建一个vue.config.js文件(和package.json同层次目录),然后配置文件如下:
module.exports = {
devServer: {
proxy: {
'/api': {//即加上前缀,强制走代理,否则public里有的就不会走代理
target: 'http://127.0.0.1:3000/api/',
changeOrigin: true,//用于控制请求头中的host值
// ws:true,//用于支持websocket
pathRewrite: {//路径重写
'^/api': ''
}
}
},
},
};
五、运行项目
1.从server文件夹打开命令行启动后端服务:
node index
2.启动vue项目:
npm run serve
3.结果展示:
总结
数据库表结构较简单,不展示。
项目基于Vue3.0创建。