vue+element-ui實現表格中的刪除按鈕加載動畫

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
真棒!又學到了新的知識!!加油

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章