在使用 VUE + Element-UI 开发项目的时候,遇到了这样一个需求:
在使用el-table
表格渲染数据的时候,有一个 “状态” 列和一个 “动作” 列。
当后端传递给我们当前行的 status = 1
的时候,状态列文字为可用(绿色),中间按钮显示为 “过期”;
当 status = 2
的时候状态列文字为禁用(红色),中间按钮显示为 “生效”,且 “编辑” 和 “删除” 按钮为禁用状态。
并且,需要在点击中间按钮的时候,在这两种状态之间进行切换。
实现思路:
- 用
el-table-column
循环渲染数据时,不要将 状态列 和 动作列 循环进去;将 状态列 单独抽离出来,写在倒数第二列,动作列 写在倒数第一列 - 通过
获取到当前行的值,在 状态列 中,放置一个 div,并且给 div 动态绑定一个 style 属性:
:style="{ color: scope.row.status =='1' ? 'green' : 'red' }"
;再通过插值语法,在 div 根据 status 的值来判断显示 可用 还是 禁用:{{ scope.row.status== '1' ? '可用' : '禁用' }}
,这样,状态列 就完成了 - 对于 动作列 来说,也是通过
获取到当前行的值,然后通过 el-button 的
:disabled
属性,动态绑定一个三元表达式来判断 编辑 和 删除 是否禁用::disabled="scope.row.status == '1' ? false : true"
,过期 和 生效 的动态切换也是同理。
完整HTML代码
<template v-for="item in listTitle">
<el-table-column
:key="item.key"
:column-key="item.prop"
:prop="item.prop"
:label="item.label"
:width="item.width"/>
</template>
<el-table-column
label="状态">
<template slot-scope="scope">
<div :style="{ color: scope.row.status =='1' ? 'green' : 'red' }">
{{ scope.row.status== '1' ? '可用' : '禁用' }}
</div>
</template>
</el-table-column>
<el-table-column
label="动作">
<template slot-scope="scope">
<el-button-group>
<el-button :disabled="scope.row.status == '1' ? false : true">编辑</el-button>
<el-button @click="rowOverdue(scope.row)">{{ scope.row.status == '1' ? '过期' : '生效' }}</el-button>
<el-button :disabled="scope.row.status == '1' ? false : true">删除</el-button>
</el-button-group>
</template>
</el-table-column>
点击 “过期” / “生效” 触发的函数代码
这里需要根据每个人自己的不同需求来进行书写,我只贴了我自己的部分代码
rowOverdue
:点击中间按钮触发的函数
overDueForm
:后端需要你传递过去的值
overdue
:后端提供的改变 status 值的接口
rowOverdue(row) {
let overDueForm = {
id: row.id,
status: row.status
}
// 改变 status 值的接口
overdue(overDueForm).then(res => {
****
})
},
总结:
本质上都是通过 来获取到当前行的值,然后再利用 三元表达式 来进行判断,根据需求显示不同的东西。