bootstrapTable中使用bootstrapSwitch
bootstrapTable中使用bootstrapSwitch
需求: 在列表中新增一列状态栏, 使用switch控件显示状态, 并且支持状态改变, 点击控件,出现一个弹窗,发送请求, 请求成功, 改变控件状态, 不成功, 状态不变
前提: 列表使用的是bootstrapTable, amd + jquery的项目, 所以switch控件自然就用的是 bootstrapSwitch, 但是这个控件官网文档地址确实找不到
bootstrapTable的一半用法通常是
-
在html结构中,头部通过link引入bootstrap-table的css, bootstrap-switch的css 给出一个table
<link href='/.../bootstrap-table.css' rel='stylesheet'></link> <link href='/.../bootstrap-switch.css' rel='stylesheet'></link> ... <table id='table'></table> -
在js中先引入 bootstrapTable, bootstrapSwitch, 因为是amd的项目, 所以使用的是define的方式,注意在入口文件main里面引入 bootstrap-table, bootstrap-switch, 通常属于 paths里面的
// main里面的内容 path: { 'bootstrapSwitch': '/lib/bootstrap-switch', 'bootstrapTable': '/lib/bootstrap-table', } // 对应的js文件 define(['jquery', 'bootstrapTable', 'bootstrapSwitch'], function($,bootstrapTable, bootstrapSwitch)) { function initTable() { var tableInit = new Object() tableInit.Init = function() { $("#table").bootstrapTable('destroy').bootstrapTable({ ajaxOptions: { headers: { 'Authorization': token } }, url: '这是一个url', method: 'get/post', ... column: [ ... { field: 'status', title: '状态', visible: true, align: 'center', width: 100, formatter: function (value, row, index) { return `<input type="checkbox" name="status" value=${row.status} />` } }, ... ] }), onLoadSuccess: function(data) { $("[name='listIsDelete']").bootstrapSwitch({ onText: '开启', onColor: 'success', offText: '关闭', offColor: 'danger', size: 'small', onSwitchChange: function(e, state) { let that = this $(this).bootstrapSwitch('state', !state, true) setTimeout(() => { // 在异步操作中改变switch控件的状态 $(that).bootstrapSwitch('toggleState', true) },1000) } }) } } } function init() { var iTable = new initTable() iTable.Init() } return { init: init } } -
基本操作就是这个样子, 在对应列里面放一个formatter: return一个checkbox, 然后在数据下载完成事件里面onLoadSuccess: 去处理对应的bootstrapSwitch控件
-
里面有两个重要方法
$(this).bootstrapSwitch('state', !state, true) // 这个是阻止控件发生改变的方法, 源码有点复杂, 没看懂, 如果只有两个参数的话(没有true),会改变控件的状态, 但是马上就会报错, 堆栈溢出, 目测是因为改变状态后会再次触发这个方法, 一直循环下去. 加一个true, 就不会触发控件改变的方法 $(that).bootstrapSwitch('toggleState', true) // 改变控件的状态, 注意不是将状态变成true, 而是改变基本这样就可以了
记录一下解决过程
之前有遇到过这种问题, 项目用的是vue + elementui, 所以使用的是el-radio-button, 文档里面的api就提供了一个change事件, 就是点击不同项之后触发的事件,并且一旦点击就会选中被点击的那一项,就是状态马上发生改变, 跟bootstrapSwitch是一样的, 所以要实现点击,弹框,发送请求, 请求成功, 状态改变,有点麻烦.
我记得当时应该是这么做的,
- 禁用掉el-radio-button, 并且将disabled的样式改成正常情况下的样式,冒充正常的el-radio-button
- 给el-radio-button注册click事件, 如果不行的话, 在el-radio-button外面包裹一层div, 注册click事件
- 在click事件中,实现弹窗, 请求, 然后改变数据的状态, 得益于vue的数据追踪, el-radio-button的显示会自动改变
所以看到这个需求第一想法是复刻之前的做法, 添加disabled, 注册事件, 弹窗, 请求, 手动改变状态,但是一开始就出问题了, 不管是给checkbox注册click事件, 还是外面包裹一层div,在div上面注册事件, 都没法成功,因此只能退而求其次, 在点击之后,状态发生改变, 同时弹窗, 如果弹窗取消或请求失败, 刷新列表或手动将状态改回去, 这样做勉强实现了功能, 但是用户体验极差, 后来才在一些论坛上面看到有这种做法,改了之后才算做好了.
所以, 为啥bootstrapSwitch 没有一个像样的中文文档?

浙公网安备 33010602011771号