前端遇到一个需求:
修改按钮:
1.没有勾选不可点击
2.勾选多个也不能点击
3.勾选行的状态为1(保存状态)才能修改
很简单的问题
<el-button type="warning"size="small" icon="el-icon-edit-outline" @click="edit()":disabled="!($refs.table&& $refs.table.getCheckboxRecords().length === 1 && $refs.table.getCheckboxRecords()[0].state === 0)"plain>修改</el-button>
!($refs.table &&
$refs.table.getCheckboxRecords().length === 1 &&
$refs.table.getCheckboxRecords()[0].state === 0)
正向思维 加限制条件直接取反
另一个思路:有点不好理解
<el-button type="warning"size="small" icon="el-icon-edit-outline" @click="edit()":disabled="$refs.table && ($refs.table.getCheckboxRecords().filter((item) => item.status !== '1').length !== 0 || $refs.table.getCheckboxRecords().length !== 1)"plain>修改</el-button>
他的写法比较巧妙 分析一下:
$refs.table && ($refs.table.getCheckboxRecords().filter((item) => item.status !== '1').length !== 0 || $refs.table.getCheckboxRecords().length !== 1)"
这一句有三个条件
$refs.table
当前页面有这个引用 返回true 这个是固定条件(ture)
($refs.table.getCheckboxRecords().filter((item) => item.status !== '1').length !== 0 || $refs.table.getCheckboxRecords().length !== 1)
他很巧妙的运用了逻辑或 || 这个运算符
|| 逻辑或运算符 两个条件只要有一个为true 就返回true 两个条件都为false 返回false
为什么说他很巧妙的运用了这个逻辑或运算符
为了简便说 把||前后分为AB条件
$refs.table.getCheckboxRecords().filter((item) => item.status !== '1').length !== 0 === A条件
$refs.table.getCheckboxRecords().length !== 1 === B条件
要想不禁用删除按钮 需要A条件和B条件都为false
什么时候AB都为false呢? 选择一个 并且状态为1 才返回false
他利用了 || 的特性 + disable false时为正常 true为禁用 我个人感觉是比较厉害的 我写不出来这样的运算 对我的感触就是逆向思维 没想到|| 还可以这样用