5、修改删除功能
2020-03-05 本文已影响0人
wqjcarnation
参考:https://www.jianshu.com/p/7dfdcc058651
目标
- 修改
- 删除
调整css
<style>
.nav{
text-align: left;
height:50px;
margin:10px;
}
.el-main{
line-height: 0;
}
</style>
修改
选定table表格-自定义列模板中的修改删除功能
image.png1、拷贝代码到页面FindAllUser.vue
<el-table-column label="操作">
<template slot-scope="scope">
<el-button
size="mini"
@click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button
size="mini"
type="danger"
@click="handleDelete(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
methods里新增加如下两个方法
methods: {
。。。。
handleEdit(index, row) {
console.log(index, row);
},
handleDelete(index, row) {
console.log(index, row);
}
。。。。
}
改造修改方法
handleEdit(index, row) {
//console.log(index, row);
//alert(row.id);
//请求后台,通过id查询指定用户的信息
this.$axios.get("http://localhost:8082/vue-servlet/getUserById?id="+row.id)
.then(response=>{
console.log(response);
//查询成功之后,携带用户信息进修改页
this.$router.push({path:'/updateUser',
query:response.data.list[0]
})
})
.catch(error=>{
console.log(error);
})
目前完整findalluser.vue代码
<template>
<div>
<el-table
ref="multipleTable"
:data="tableData"
tooltip-effect="dark"
style="width: 100%"
@selection-change="handleSelectionChange">
<el-table-column
type="selection"
width="55">
</el-table-column>
<el-table-column
prop="userName"
label="用户名"
width="120">
</el-table-column>
<el-table-column
prop="email"
label="邮箱"
width="200">
</el-table-column>
<el-table-column
prop="idCard"
label="身份证号"
width="200">
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button
size="mini"
@click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button
size="mini"
type="danger"
@click="handleDelete(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
background
layout="prev, pager, next"
:total="total"
:page-size="pageSize"
@current-change="changePage">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
multipleSelection: [],
//以下三个是分页相关的属性
total:0,//查询得到
pageSize:2,//每页条数
currentPage:1,
dialogFormVisible: false,
}
},
mounted(){
//调用查询所有用户的方法
this.findAll();
},
methods: {
toggleSelection(rows) {
if (rows) {
rows.forEach(row => {
this.$refs.multipleTable.toggleRowSelection(row);
});
} else {
this.$refs.multipleTable.clearSelection();
}
},
handleSelectionChange(val) {
this.multipleSelection = val;
},
findAll(){
//请求后台,查询所有用户
this.$axios.get("http://localhost:8082/vue-servlet/findAllUser",
{params:{currentPage:this.currentPage,pageSize:this.pageSize}})
.then(response=>{
let data=response.data;//后台的responseBean
//用响应数据去更新
this.tableData=data.list;
this.total=data.page.count;
})
.catch()
},
changePage:function(currentPage){
//alert(`当前页${currentPage}`);
this.currentPage=currentPage;
this.findAll();
},
handleEdit(index, row) {
//console.log(index, row);
//alert(row.id);
//请求后台,通过id查询指定用户的信息
this.$axios.get("http://localhost:8082/vue-servlet/getUserById?id="+row.id)
.then(response=>{
console.log(response);
//查询成功之后,携带用户信息进修改页
this.$router.push({path:'/updateUser',
query:response.data.list[0]
})
})
.catch(error=>{
console.log(error);
})
},
handleDelete(index, row) {
//console.log(index, row);
alert(row.id);
//请求后台,通过id删除指定用户的信息
//删除成功之后,重新调用findall
}
}
}
</script>
<style>
.nav{
text-align: left;
height:50px;
margin:10px;
}
.el-main{
line-height: 0;
}
</style>
编写修改页面UpdateUser.vue
该页获取上一面传过来的数据用 this.$route.query.字段名
在添加页基础上进行微调,把id带到后台,前台不可编辑
<template>
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="用户名" prop="username">
<el-input v-model="ruleForm.username"></el-input>
</el-form-item>
<el-form-item label="邮箱" prop="email">
<el-input v-model="ruleForm.email"></el-input>
</el-form-item>
<el-form-item label="身份证号" prop="idcard">
<el-input v-model="ruleForm.idcard"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
</template>
<script>
export default {
data() {
return {
ruleForm: {
id:this.$route.query.id,
username: this.$route.query.userName,
email: this.$route.query.email,
idcard: this.$route.query.idCard,
power:this.$route.query.power
},
rules: {
//required是否必填项 trigger:触发方式 blur:表示离开焦点时 message:错误提示
username: [
{ required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
],
//trigger: 'blur' trigger: ['blur', 'change']
email:[
{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
],
idcard:[
{ min: 15, max: 18, message: '长度在 15 到 18 个字符', trigger: ['blur'] }
]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
//alert('submit!');
//step 1,把form转换成json字符串形式
let obj=this.$qs.stringify(this.ruleForm);
//step 2计划在这里用axios去给后台发送修改请求 (url,data) data-json
this.$axios.post('http://localhost:8082/vue-servlet/updateUser',obj)
.then(response=>{
//step 3如果响应后,我们再做后处理 --json
alert(response.data.msg);
this.$router.push({path:'findalluser'})
})
.catch(error=>{
console.log(error)
})
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
<style>
</style>
为修改配置路由
{
path: '/updateUser',
name: 'UpdateUser',
component: UpdateUser
}
编写后台修改方法
GetUserServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id=request.getParameter("id");
//调用service,根据id查询
IUserService us=new UserServiceImpl();
User db_user=null;
try {
db_user = us.getUserById(Integer.parseInt(id));
} catch (NumberFormatException | ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResponseBean resp=new ResponseBean();
resp.setCode("0");
resp.setMsg("success");
List<User> userList=new ArrayList();
userList.add(db_user);
resp.setList(userList);
ObjectMapper om=new ObjectMapper();
String json=om.writeValueAsString(resp);
response.getWriter().print(json);
}
AdminUpdServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取前台页面传过来的参数
String id = request.getParameter("id");
String name = request.getParameter("username");
String email = request.getParameter("email");
String idCard = request.getParameter("idcard");
String power = request.getParameter("power");
// 封装user对象
User user = new User();
user.setId(Integer.parseInt(id));
user.setUserName(name);
user.setEmail(email);
user.setIdCard(idCard);
user.setPower(Integer.parseInt(power));
// 调用service进行修改操作
IUserService service = new UserServiceImpl();
int i=0;
try {
i = service.update(user);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResponseBean rm = new ResponseBean();
if(i>0){
rm.setCode("0");
rm.setMsg("修改成功");
}else{
rm.setCode("-1");
rm.setMsg("修改失败");
}
// 数据返回到页面
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(rm);
System.out.println(json);
response.getWriter().append(json);
}
dao:
@Override
public User getUserById(String id) {
User dbuser=null;
conn=DBUtil.getConnection();
try {
ps=conn.prepareStatement("select * from t_user where user_id=? ");
ps.setInt(1, Integer.parseInt(id));
rs=ps.executeQuery();
if(rs.next()){//如果有该用户
dbuser=new User();
dbuser.setId(rs.getInt("user_id"));
dbuser.setUserName(rs.getString("user_name"));
dbuser.setUserPwd(rs.getString("user_pwd"));
dbuser.setEmail(rs.getString("user_email"));
dbuser.setIdCard(rs.getString("user_idcard"));
dbuser.setPower(rs.getInt("user_power"));
}
} catch (SQLException e) {
e.printStackTrace();
}
DBUtil.closeConnection(rs, ps, conn);
return dbuser;
}
@Override
public int update(User user) {
int i=0;
try {
conn=DBUtil.getConnection();
ps=conn.prepareStatement("update t_user set user_name=?,user_email=?,user_idcard=?,user_power=? where user_id=? ");
ps.setString(1,user.getUserName());
ps.setString(2,user.getEmail());
ps.setString(3,user.getIdCard());
ps.setInt(4,user.getPower());
ps.setInt(5, user.getId());
i=ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
DBUtil.closeConnection(rs, ps, conn);
return i;
}
测试
image.png image.pngimage.png
新增用户的链接
用到的技术button dialog,参考element-ui官网
image.png image.png关键代码
step1 新增一个按钮,触发dialog显示
<div class="nav">
<el-button type="primary" icon="el-icon-plus" @click="dialogFormVisible = true">新增</el-button>
</div>
step2 data属性里新增dialogFormVisible
data() {
return {
tableData: [],
multipleSelection: [],
//以下三个是分页相关的属性
total: 0, //查询得到
pageSize: 2, //每页条数
currentPage: 1,
dialogFormVisible: false
}
}
step3 制作dialog
<el-dialog title="用户添加" :visible.sync="dialogFormVisible" modal="true">
</el-dialog>
step4
引用新增用户组件
import reg from '@/components/user/Register'
components: {
reg
}
<el-dialog title="用户添加" :visible.sync="dialogFormVisible" modal="true">
<reg></reg>
</el-dialog>
findalluser完整代码
<template>
<div>
<div class="nav">
<el-button type="primary" icon="el-icon-plus" @click="dialogFormVisible = true">新增</el-button>
</div>
<el-dialog title="用户添加" :visible.sync="dialogFormVisible" modal="true">
<reg></reg>
</el-dialog>
<el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55">
</el-table-column>
<el-table-column prop="userName" label="用户名" width="120">
</el-table-column>
<el-table-column prop="email" label="邮箱" width="200">
</el-table-column>
<el-table-column prop="idCard" label="身份证号" width="200">
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize" @current-change="changePage">
</el-pagination>
</div>
</template>
<script>
import reg from '@/components/user/Register'
export default {
data() {
return {
tableData: [],
multipleSelection: [],
//以下三个是分页相关的属性
total: 0, //查询得到
pageSize: 2, //每页条数
currentPage: 1,
dialogFormVisible: false
}
},
mounted() {
//调用查询所有用户的方法
this.findAll();
},
methods: {
toggleSelection(rows) {
if (rows) {
rows.forEach(row => {
this.$refs.multipleTable.toggleRowSelection(row);
});
} else {
this.$refs.multipleTable.clearSelection();
}
},
handleSelectionChange(val) {
this.multipleSelection = val;
},
findAll() {
//请求后台,查询所有用户
this.$axios.get("http://localhost:8082/vue-servlet/findAllUser", {
params: {
currentPage: this.currentPage,
pageSize: this.pageSize
}
})
.then(response => {
let data = response.data; //后台的responseBean
//用响应数据去更新
this.tableData = data.list;
this.total = data.page.count;
})
.catch()
},
changePage: function(currentPage) {
//alert(`当前页${currentPage}`);
this.currentPage = currentPage;
this.findAll();
},
handleEdit(index, row) {
//console.log(index, row);
//alert(row.id);
//请求后台,通过id查询指定用户的信息
this.$axios.get("http://localhost:8082/vue-servlet/getUserById?id=" + row.id)
.then(response => {
console.log(response);
//查询成功之后,携带用户信息进修改页
this.$router.push({
path: '/updateUser',
query: response.data.list[0]
})
})
.catch(error => {
console.log(error);
})
},
handleDelete(index, row) {
//console.log(index, row);
alert(row.id); //是实体类的属性 是主键,不是索引
//请求后台,通过id删除指定用户的信息
//删除成功之后,重新调用findall
}
},
components: {
reg
}
}
</script>
<style>
.nav {
text-align: left;
height: 50px;
margin: 10px;
}
.el-main {
line-height: 0;
}
</style>
效果
image.png image.png