vue+element-ui实现表格中的删除按钮加载动画
背景:
在同事的项目中有这样的一个要求:
就在在表格中的操作栏有一个删除按钮,点击的时候加载loading的动画,加载完毕后loading动画停止。
同事开始的时候是全局定义一个isLoading的变量来控制,
结果发现每点击一个删除按钮,就会导致所有的按钮加载loading动画。
真棒!bug又出现了,琢磨了代码一番,于是有了一下的方案!
思路
导致bug的原因是因为共用这个全局的变量,既然全局不行,那么我们就可以从每一行来控制
1.放弃data里定义一个isLoading
2.在拿到整个表格的数据之后,做一番处理,就是每遍历一个item对象,就往其中加入一个isLoading的属性,并赋值为false
3.在点击删除的时候就给row.isLoading赋值为true,等删除成功后设置为row.isLoading=false.
4.通过以上步骤即可实现删除按钮的loading动画
代码实现
html部分
<el-table :data="tableData" style="width: 100%" border>
<el-table-column label="日期" width="180">
<template slot-scope="scope">
<i class="el-icon-time"></i>
<span style="margin-left: 10px">{{ scope.row.date }}</span>
</template>
</el-table-column>
<el-table-column label="姓名" width="180">
<template slot-scope="scope">
<el-popover trigger="hover" placement="top">
<p>姓名: {{ scope.row.name }}</p>
<p>住址: {{ scope.row.address }}</p>
<div slot="reference" class="name-wrapper">
<el-tag size="medium">{{ scope.row.name }}</el-tag>
</div>
</el-popover>
</template>
</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" :loading="scope.row.isLoading" type="danger"
@click="handleDelete(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
javascript部分
var vm = new Vue({
el: "#app",
data: {
tableData: []
},
mounted() {
this.handleFormat()
},
methods: {
async handleFormat() {
const {
data
} = await axios.get('./data.json');
data.forEach(item => {
item['isLoading'] = false;
this.tableData.push(item)
})
},
handleEdit(index, row) {
console.log(index, row);
},
handleDelete(index, row) {
row.isLoading = true;
this.$confirm('此操作将进行删除操作, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$message({
type: 'success',
message: '删除成功!'
});
setTimeout(function () {
row.isLoading = false;
}, 1500)
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
row.isLoading = false;
});
}
}
})
效果展示
ending
真棒!又学到了新的知识!!加油