1. 正文
1、elementui布局框架
2、使用elementui+vue+axios完成一個(gè)案例。
2.elementui布局框架
Element,一套為開發(fā)者、設(shè)計(jì)師和產(chǎn)品經(jīng)理準(zhǔn)備的基于?Vue?2.0?的桌面端組件庫?。
換句話說:Element它是再vue2.0得基礎(chǔ)上,提供了各種組件(比如表單?表格?菜單導(dǎo)航.....),使用這些組件可以更好得完成功能和布局。
這些組件我們使用誰我們就講誰,你們要主要看看我是如何使用這些組件得,那么你再使用其他組件時(shí)也可以按照這種方式來用。
2.1如何使用elementui組件
(1)需要再相應(yīng)得網(wǎng)頁中引入vue和elementui得文件
注意:==必須先引入vue在引入element==
<!--引入element得css樣式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 這個(gè)必須在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
(2)設(shè)置表格組件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--引入element得css樣式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 這個(gè)必須在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<!--創(chuàng)建一個(gè)標(biāo)簽使vue掛載到該標(biāo)簽上-->
<div id="app">
<!--:data==綁定了vue中定義得數(shù)據(jù)tableData
border表示設(shè)置表格邊框
el-table-column:表示列標(biāo)簽
prop:該屬性得名稱必須和tableData中對象得屬性名一致。
label:表格得標(biāo)題
width: 設(shè)置列得寬度
-->
<el-table
:data="tableData"
border
style="width: 100%">
<el-table-column
prop="date"
label="日期"
>
</el-table-column>
<el-table-column
prop="name"
label="姓名"
>
</el-table-column>
<el-table-column
prop="address"
label="地址">
</el-table-column>
<el-table-column
fixed="right"
label="操作"
>
<template slot-scope="scope">
<el-button type="text" size="small">查看</el-button>
<el-button type="text" size="small">編輯</el-button>
</template>
</el-table>
</div>
</body>
<!--表示自定義得js文件-->
<script>
var app=new Vue({
el:"#app",
data:{
tableData:[
{"date":"2020-05-11","name":"張三","address":"北京"},
{"date":"2021-05-11","name":"李四","address":"鄭州"},
{"date":"2022-05-11","name":"五五","address":"杭州"},
{"date":"2023-06-11","name":"六六","address":"上海"},
],
}
})
</script>
</html>
把上面得操作文字換成按鈕形式:
<el-table-column
fixed="right"
label="操作"
>
<template slot-scope="scope">
<el-button type="success" size="small" icon="el-icon-edit" plain>編輯</el-button>
<el-button type="danger" size="small" icon="el-icon-delete" plain>刪除</el-button>
</template>
</el-table-column>
瀏覽器并沒有顯示圖標(biāo)得樣式:我們需要引入下面三個(gè)文件到工程中
3. elementui+axios+后臺代碼
我們上面的表格數(shù)據(jù)都是死數(shù)據(jù)。而我們實(shí)際開發(fā)中表格數(shù)據(jù)應(yīng)該從后臺數(shù)據(jù)庫中查詢獲取的。
-- 創(chuàng)建數(shù)據(jù)庫
create database vue01;
-- 切換數(shù)據(jù)庫到vue01
use vue01;
-- 創(chuàng)建表
create table t_dept(
dept_id int primary key auto_increment COMMENT '部門號',
dept_name varchar(20) COMMENT '部門名稱',
loc varchar(20) COMMENT '部門所在地'
);
create table t_emp(
emp_id int primary key auto_increment COMMENT '員工編號',
emp_name varchar(20) COMMENT '員工姓名',
emp_sex TINYINT COMMENT '性別 0表示男 1表示女',
emp_age int COMMENT '年齡',
emp_salary DECIMAL(7,2) COMMENT '工資',
dept_id int COMMENT '關(guān)聯(lián)的部門號'
);
-- 添加數(shù)據(jù)
insert into t_dept values
(null,'研發(fā)部','鄭州'),(null,'市場部','杭州'),(null,'人事部','北京')
insert into t_emp values
(null,'張三',0,25,1666.65,1),
(null,'李四',1,26,2555.65,2),
(null,'王五',0,32,6666.65,3),
(null,'趙六',0,36,8888.65,1)
(2)創(chuàng)建員工實(shí)體類
package com.aaa.entity;
/**
* @program: vue01-qy151
* @description: 員工表的實(shí)體類
* @author: ysh
* @create: 2022-05-26 15:21
**/
public class Emp {
//員工編號
private int empId;
//員工姓名
private String empName;
//性別
private int empSex;
//年齡
private int empAge;
//薪水
private Double empSalary;
//部門號
private int deptId;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpSex() {
return empSex;
}
public void setEmpSex(int empSex) {
this.empSex = empSex;
}
public int getEmpAge() {
return empAge;
}
public void setEmpAge(int empAge) {
this.empAge = empAge;
}
public Double getEmpSalary() {
return empSalary;
}
public void setEmpSalary(Double empSalary) {
this.empSalary = empSalary;
}
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
}
(3)員工的dao
/**
* 查詢所有員工信息
* @return 所有員工信息
*/
public List<Emp> findAll(){
List<Emp> list = new ArrayList<>();
try {
getConn();
String sql="select * from t_emp";
ps=connection.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
Emp emp=new Emp();
emp.setEmpId(rs.getInt("emp_id"));
emp.setEmpName(rs.getString("emp_name"));
emp.setEmpAge(rs.getInt("emp_age"));
emp.setEmpSalary(rs.getDouble("emp_salary"));
emp.setEmpSex(rs.getInt("emp_sex"));
emp.setDeptId(rs.getInt("dept_id"));
list.add(emp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll();
}
return list;
}
(4)測試dao方法
package com.aaa.test;
import com.aaa.dao.EmpDao;
import org.junit.Test;
/**
* @program: vue01-qy151
* @description:
* @author: ysh
* @create: 2022-05-26 15:30
**/
public class TestEmpDao {
private EmpDao empDao=new EmpDao();
@Test
public void testFindAll(){
System.out.println(empDao.findAll());
}
}
(5)controller
package com.aaa.controller;
import com.aaa.dao.EmpDao;
import com.aaa.entity.Emp;
import com.alibaba.fastjson.JSON;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet(name = "EmpServlet",urlPatterns = "/EmpServlet")
public class EmpServlet extends HttpServlet {
private EmpDao empDao=new EmpDao();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//接受處理的標(biāo)識
String method = req.getParameter("method");
if("delete".equals(method)){
}else{
//查詢所有的操作
queryAll(req,resp);
}
}
private void queryAll(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
List<Emp> list = empDao.findAll();
//把java集合轉(zhuǎn)換為json對象。---fastjson
String result = JSON.toJSONString(list);
PrintWriter writer = resp.getWriter();
//輸出給客戶
writer.print(result);
//關(guān)閉資源
writer.flush();
writer.close();
}
}
(6)展示到網(wǎng)頁
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--引入element得css樣式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 這個(gè)必須在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<!--創(chuàng)建一個(gè)標(biāo)簽使vue掛載到該標(biāo)簽上-->
<div id="app">
<!--:data==綁定了vue中定義得數(shù)據(jù)tableData
border表示設(shè)置表格邊框
el-table-column:表示列標(biāo)簽
prop:該屬性得名稱必須和tableData中對象得屬性名一致。
label:表格得標(biāo)題
width: 設(shè)置列得寬度
-->
<el-table
:data="tableData"
border
style="width: 100%">
<el-table-column
prop="empId"
label="員工編號"
>
</el-table-column>
<el-table-column
prop="empName"
label="員工姓名"
>
</el-table-column>
<el-table-column
prop="empSex"
label="性別">
</el-table-column>
<el-table-column
prop="empAge"
label="年齡">
</el-table-column>
<el-table-column
prop="empSalary"
label="薪水">
</el-table-column>
<el-table-column
prop="deptId"
label="部門編號">
</el-table-column>
<el-table-column
fixed="right"
label="操作"
>
<template slot-scope="scope">
<el-button type="success" size="small" icon="el-icon-edit" plain>編輯</el-button>
<el-button type="danger" size="small" icon="el-icon-delete" plain>刪除</el-button>
</template>
</el-table-column>
</el-table>
</div>
</body>
<!--表示自定義得js文件-->
<script>
var app=new Vue({
el:"#app",
data:{
tableData:[],
},
//頁面加載完畢后執(zhí)行;
created(){
this.initTable();
},
methods:{
//初始化表格數(shù)據(jù)
initTable(){
var that=this;
//通過axios后臺服務(wù)發(fā)送異步請求
axios.post("EmpServlet").then(function(result){
if(result.data.code===2000){//===:比較值和引用是否相同
that.tableData=result.data.data;
}else{
}
})
}
}
})
</script>
</html>
我們發(fā)現(xiàn)上面的性別顯示的為數(shù)字 如何顯示男和女呢 我們需要自定義列
<el-table-column
prop="empSex"
label="性別">
<template slot-scope="scope">
<el-tag size="medium"> {{ scope.row.empSex==0?"男":"女" }}</el-tag>
</template>
</el-table-column>
4.刪除
(1)前端
var qs=Qs; axios.post("EmpServlet",qs.stringify({"method":"delete","id":id})).then(function(result){
that.initTable();
})
axios底層post提交的參數(shù)會封裝到request playload請求載體中,使用request.getParamter是無法接受到請求載體的參數(shù), request.getParamter它只能接受query param參數(shù)和form data參數(shù)。我們可以借助qs把請求載體的參數(shù)轉(zhuǎn)換為form data參數(shù)。轉(zhuǎn)換的步驟
(1)?在網(wǎng)頁中引入qs
????<script?type="text/javascript"?src="js/qs.min.js"></script>
(2)?把Qs對象重寫賦值一個(gè)參數(shù)
????var?qs=Qs;
(3)?把??request?playload使用?stringify方法轉(zhuǎn)換
qs.stringify({"":"","":""})
(2)servlet
private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
String id = req.getParameter("id");
int row=empDao.delete(id);
PrintWriter writer = resp.getWriter();
if(row==1){ //刪除成功
CommonResult commonResult=new CommonResult(2000,"刪除成功",null);
writer.print(JSON.toJSONString(commonResult));
}else{ //刪除失敗
CommonResult commonResult=new CommonResult(5000,"刪除失敗",null);
writer.print(JSON.toJSONString(commonResult));
}
writer.flush();
writer.close();
}
(3) dao
//刪除操作
public int delete(String id) {
String sql ="delete from t_emp where emp_id=?";
return edit(sql,id);
}
5.添加功能
點(diǎn)擊添加按鈕顯示一個(gè)彈出層
<el-dialog
title="添加員工"
:visible.sync="addDialogVisible"
width="30%"
>
<!--:model==綁定表單數(shù)據(jù)-->
<el-form :model="addform">
<el-form-item label="姓名" label-width="40px">
<el-input v-model="addform.empName" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="性別" label-width="40px">
<el-radio v-model="addform.empSex" :label="0">男</el-radio>
<el-radio v-model="addform.empSex" :label="1">女</el-radio>
</el-form-item>
<el-form-item label="年齡" label-width="40px">
<el-input v-model="addform.empAge" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="薪水" label-width="40px">
<el-input v-model="addform.empSalary" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="addDialogVisible = false">取 消</el-button>
<el-button type="primary" @click="">確 定</el-button>
</span>
</el-dialog>
(2)添加點(diǎn)擊事件
//添加的點(diǎn)擊事件
addEmp(){
var qs=Qs;
var that=this;
axios.post("EmpServlet?method=insert",qs.stringify(this.addform)).then(function(result){
if(result.data.code===2000){
that.$message.success(result.data.msg);
that.initTable();//重新加載表格
that.addDialogVisible=false;
}
})
}
(3)添加servlet
//添加
private void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
String name = req.getParameter("empName");
String sex = req.getParameter("empSex");
String age = req.getParameter("empAge");
String salary = req.getParameter("empSalary");
Emp emp = new Emp(name,Integer.parseInt(sex),Integer.parseInt(age),Double.parseDouble(salary));
int row=empDao.add(emp);
PrintWriter writer = resp.getWriter();
if(row==1){ //添加成功
CommonResult commonResult=new CommonResult(2000,"添加成功",null);
writer.print(JSON.toJSONString(commonResult));
}else{ //添加失敗
CommonResult commonResult=new CommonResult(5000,"添加失敗",null);
writer.print(JSON.toJSONString(commonResult));
}
writer.flush();
writer.close();
}
(4)dao的代碼
/**
* 添加功能
* @param emp
* @return
*/
public int add(Emp emp) {
String sql="insert into t_emp(emp_name,emp_sex,emp_age,emp_salary) values(?,?,?,?)";
return edit(sql,emp.getEmpName(),emp.getEmpSex(),emp.getEmpAge(),emp.getEmpSalary());
}
6.修改功能
(1)點(diǎn)擊編輯回顯數(shù)據(jù)
<!--修改員工的對話框-->
<el-dialog
title="修改員工"
:visible.sync="editDialogVisible"
width="30%"
>
<!--:model==綁定表單數(shù)據(jù)-->
<el-form :model="editform" :rules="addRules" ref="addRuleForm">
<el-form-item label="姓名" label-width="80px" prop="empName">
<el-input v-model="editform.empName" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="性別" label-width="80px">
<el-radio v-model="editform.empSex" :label="0">男</el-radio>
<el-radio v-model="editform.empSex" :label="1">女</el-radio>
</el-form-item>
<el-form-item label="年齡" label-width="80px" prop="empAge">
<el-input v-model.number="editform.empAge" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="薪水" label-width="80px">
<el-input v-model="editform.empSalary" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="editDialogVisible = false">取 消</el-button>
<el-button type="primary" @click="editEmp">確定修改</el-button>
</span>
</el-dialog>
注意: ==:visible.sync="editDialogVisible" 一定要在vue data中定義editDialogVisible :model="editform" 保證在vue data中定義editform==
<el-button @click="edit(scope.row)" type="success" size="small" icon="el-icon-edit" plain>編輯</el-button>
//修改按鈕點(diǎn)擊事件
edit(row){
//1.顯示修改彈出層
this.editDialogVisible=true;
//2.數(shù)據(jù)回顯
this.editform=row;
},
(2) 點(diǎn)擊確認(rèn)修改按鈕
<el-button type="primary" @click="editEmp">確定修改</el-button>
//確認(rèn)修改
editEmp(){
var that=this;
var qs=Qs;
this.$refs['editRuleForm'].validate((valid) => {
if (valid) { //表單校驗(yàn)通過
axios.post("EmpServlet?method=edit",qs.stringify(this.editform)).then(function(result){
if(result.data.code===2000){
that.$message.success(result.data.msg);//彈出成功的消息
that.editDialogVisible=false; //隱藏修改對話框
that.initTable(); //重新加載表格數(shù)據(jù)
}
})
}
});
},
servlet:
//修改操作
private void edit(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
String name = req.getParameter("empName");
String sex = req.getParameter("empSex");
String age = req.getParameter("empAge");
String salary = req.getParameter("empSalary");
String id = req.getParameter("empId");
Emp emp = new Emp(Integer.parseInt(id),name,Integer.parseInt(sex),Integer.parseInt(age),Double.parseDouble(salary));
int row=empDao.update(emp);
PrintWriter writer = resp.getWriter();
if(row==1){ //刪除成功
CommonResult commonResult=new CommonResult(2000,"修改成功",null);
writer.print(JSON.toJSONString(commonResult));
}else{ //刪除失敗
CommonResult commonResult=new CommonResult(5000,"修改失敗",null);
writer.print(JSON.toJSONString(commonResult));
}
writer.flush();
writer.close();
}
dao:
/**
* 修改功能
* @param emp
* @return
*/
public int update(Emp emp) {
String sql = "update t_emp set emp_name=?,emp_sex=?,emp_age=?,emp_salary=? where emp_id=?";
return edit(sql,emp.getEmpName(),emp.getEmpSex(),emp.getEmpAge(),emp.getEmpSalary(),emp.getEmpId());
}
7.登錄
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登錄頁面</title>
<!--引入element得css樣式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 這個(gè)必須在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
<style>
/*body{
background: url("imgs/1.webp") no-repeat;
}*/
body,.box{
overflow: hidden;
height: 100%;
}
.box{
background: url("imgs/1.webp") no-repeat;
}
#loginBox {
width: 450px;
height: 300px;
background: white;
border-radius: 3px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
#loginBox>.avatar_box{
height: 130px;
width: 130px;
border: 1px solid #eee;
border-radius: 50%;
padding: 10px;
box-shadow: 0 0 10px #ddd;
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
}
#loginBox>.avatar_box>img {
width: 100%;
height: 100%;
border-radius: 50%;
background-color: #eee;
}
.login_form {
position: absolute;
bottom: 0;
width: 100%;
padding: 0 20px;
box-sizing: border-box;
}
</style>
</head>
<body background="imgs/3.webp">
<div class="box">
<div id="loginBox">
<!-- 頭像 -->
<div class="avatar_box">
<img src="imgs/1.jpg" />
</div>
<el-form label-width="80px" :model="loginForm" :rules="rules" ref="loginFormRef" class="login_form">
<el-form-item label="賬號:" prop="username">
<el-input v-model="loginForm.username"></el-input>
</el-form-item>
<el-form-item label="密碼:" prop="password">
<el-input v-model="loginForm.password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm()">登錄</el-button>
</el-form-item>
</el-form>
</div>
</div>
<script>
var app = new Vue({
el: ".box",
data: {
loginForm: {},
//校驗(yàn)規(guī)則
rules: {
username: [
{required: true, message: "請輸入賬號", trigger: "blur"},
{min: 5, max: 12, message: "賬號的長度必須{5~12}", trigger: "blur"},
],
password: [
{required: true, message: "請輸入密碼", trigger: "blur"},
{min: 6, max: 12, message: "密碼的長度必須{6~12}", trigger: "blur"},
]
}
},
methods: {
submitForm() {
var that = this;
var qs = Qs;
this.$refs['loginFormRef'].validate((valid) => {
if (valid) {
axios.post("UserServlet?method=login", qs.stringify(this.loginForm)).then(function (result) {
if (result.data.code === 2000) {
that.$message.success(result.data.msg);
location.href = "element01.html"
} else {
that.$message.error(result.data.msg);
}
});
}
})
}
}
})
</script>
</body>
</html>
(2)servlet
private void login(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
String username = req.getParameter("username");
String password = req.getParameter("password");
if("admin".equals(username)&&"123456".equals(password)){
HttpSession session = req.getSession();
session.setAttribute("username",username);
CommonResult commonResult=new CommonResult(2000,"登錄成功",null);
writer.print(JSON.toJSONString(commonResult));
}else{
CommonResult commonResult=new CommonResult(5000,"賬號或密碼錯(cuò)誤",null);
writer.print(JSON.toJSONString(commonResult));
}
writer.flush();
writer.close();
}
8.表單校驗(yàn)
Form 組件提供了表單驗(yàn)證的功能,只需要通過 rules
屬性傳入約定的驗(yàn)證規(guī)則,并將 Form-Item 的 prop
屬性設(shè)置為需校驗(yàn)的字段名即可
如果不符合表單的校驗(yàn)應(yīng)該不允許表單提交
//添加的點(diǎn)擊事件
addEmp(){
this.$refs['addRuleForm'].validate((valid) => {
if (valid) { //表單校驗(yàn)通過
var qs=Qs;
var that=this;
axios.post("EmpServlet?method=insert",qs.stringify(this.addform)).then(function(result){
if(result.data.code===2000){
that.$message.success(result.data.msg);
that.initTable();//重新加載表格
that.addDialogVisible=false; //隱藏彈出層
}
})
}
});
}
9.添加登錄過濾器
package com.qy151.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @unthor : YSH
* @date : 13:44 2022/5/29
*/
@WebFilter(filterName = "UserFilter",urlPatterns = "/*")
public class UserFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request= (HttpServletRequest) servletRequest;
HttpServletResponse response= (HttpServletResponse) servletResponse;
//1.接受請求路徑
String path = request.getRequestURI();
//2.設(shè)置放行的路徑
if(path.contains("login.html")
||path.contains("UserServlet")
||path.endsWith(".js")
||path.endsWith(".css")
||path.endsWith(".jpg")
||path.endsWith(".gif")
||path.endsWith(".jpeg")
||path.endsWith(".webp")
||path.endsWith(".png")){
filterChain.doFilter(request,response);
return;
}
//3.判斷用戶是否登錄
Object username = request.getSession().getAttribute("username");
if(username!=null){
filterChain.doFilter(request,response);
return;
}
//4.跳轉(zhuǎn)到登錄頁面
response.sendRedirect("login.html");
}
public void destroy() {
}
}