Layui表格开关按钮,点击表格开关按钮修改数据前后台代码记录
在日常开发过程中,难免少不了一些状态的修改,而打开编辑页面,修改状态再去保存无疑增加了繁琐程度,其实一直都有简单的解决办法,然鹅今天他就在这里,你用还是不用.hhhhh~
如图,这是一个菜品分类的表格,控制每一条的状态可以决定该分类是否在前端页面进行展示,这是一个简单的栗子,实际开发过程中肯定不止于此,大家举一反三。
下面给小伙伴们看一下前后端代码实现,前端最重要的是如何获取该行的唯一标识作为后台修改的参数,往下看。
首先是前端,使用Layui的表格组件自不必多说,我贴一下这个开关的实现
//在开关catesStatus后面添加templet,"#switchTpl"这个代码在html页面写,下一段则是开关点击的监听事件,使用ajax发送到后台修改数据。
CatesInfo.initColumn = function () {
return [[
{type: 'checkbox'},
{field: 'pid', align: "center", sort: true, title: '分类编码'},
{field: 'ord', align: "center", sort: true, title: '排序'},
{field: 'title', align: "center", sort: true, title: '分类名称' },
{field: 'catesStatus', align: "center", sort: true, title: '状态',templet: "#switchTpl" },
{field: 'addTime', align: "center", sort: true, title: '添加时间'},
{align: 'center', toolbar: '#tableBar', title: '操作'}
]];
};
//开关点击事件
form.on('switch(catesStatus)', function(obj){
//根据业务判断是开启还是关闭
var state = obj.elem.checked?1:0;
var pid= obj.elem.attributes['pid'].nodeValue;//获取修改数据的参数条件
var ajax = new $ax("/songtikProductCates/editState", function (data) {
Layui.success("修改成功!");
table.reload(CatesInfo.tableId);
}, function (data) {
Layui.error("修改失败!" + data.responseJSON.message + "!");
});
ajax.set("pid", pid);
ajax.set("state", state);
ajax.start();
});
Html页面代码。这里需要注意的是,你需要把该条数据的唯一标识写到属性里如:pid="{{d.pid}}" ,这样可以在后台点击事件中,取到值,作为后台修改数据的参数条件
<script id="switchTpl" type="text/html">
<input type="checkbox" name="catesStatus" value = {{d.catesStatus}} lay-skin="switch" pid="{{d.pid}}" lay-text="启用|禁用" lay-filter="catesStatus" {{d.catesStatus=='启用'?'checked':''}}>
</script>
其次是后端代码,后端使用的是Java springboot项目
控制层代码
/**
* 启用禁用接口
* @author songTiank
* @date 2021-09-28
*/
@RequestMapping("/editState")
@ResponseBody
public ResponseData editState(@RequestParam("pid") String pid,@RequestParam("state")String state) {
this.songtikProductCatesService.editState(pid,state);
return ResponseData.success();
}
服务层代码
这里使用的是mybatis-plus和代码生成器创建的方法,对数据进行修改。
@Override
public void editState(String pid, String state) {
//创建mybatis-plus查询对象
QueryWrapper<SongtikProductCates> songtikProductCatesQueryWrapper = new QueryWrapper<>();
//放入查询参数,第一个参数为数据库字段名称,需与数据库字段一致。
SongtikProductCates songtikProductCates = this.baseMapper.selectOne(songtikProductCatesQueryWrapper.eq("pid", pid));
//修改状态
songtikProductCates.setCatesStatus(Integer.parseInt(state));
//对此条数据进行更新
this.update(songtikProductCates);
}
至此,点击表格开关按钮修改状态功能实现,如果觉得有用欢迎点赞收藏哦😊
有什么问题请留言或者私信🙂