element-ui给table里的每个按钮设置loading

先上效果图:

 说明:在table中,点击不同行的发送按钮,只有此行的按钮进行加载,请求后台成功后停止加载。

具体看代码(只有前台代码):

<template>
    <el-table :data="userList" border fit class="user_table">
        <el-table-column label="姓名" prop="chinaName" align="center"></el-table-column>
        <el-table-column label="电话" prop="phone" align="center"></el-table-column>
        <el-table-column label="操 作" align="center">
            <template slot-scope="scope">
                <div class="scope_inline">
                <el-input v-model="scope.row.msg" placeholder="请输入消息" />
                <el-button type="primary" size="mini" :loading="scope.row.loading" @click="sendMsg(scope.row)">发送
                </el-button>
            </div>
            </template>
        </el-table-column>
    </el-table>
</template>

<script>
    import { user } from '@/api/user'
    export default {
        data() {
            return {
                userList: []
            }
        },
        created() {
            this.getList()
        },
        methods: {
            //查询用户列表
            getList() {
                user.getList().then(res => {
                    this.userList = res.data
                    this.userList.map(item => {
                        //添加属性,设置默认值
                        this.$set(item, 'loading', false)
                        return item
                    })
                }, err => {
                    console.log(err)
                })
            },
            //发送消息
            sendMsg(row) {
                row.loading = true
                user.sendMsg({
                    id: row.id,
                    msg: row.msg
                }).then(res => {
                    if (res.code == 200) {
                        row.loading = false
                    }
                }, err => {
                    console.log(err)
                })
            }
        },

    }

</script>

<style scoped>
    .user_table{
        width: 800px;
    }
    .scope_inline{
        display: flex;
    }
</style>

从代码可以看出,是给每一行的按钮都设置了一个加载的状态,而不是设置一个全局的变量。在请求前,设置此行的按钮为加载状态,在请求成功后取消加载。

需要注意的是,在进行网络请求中修改加载状态时,需先设置其初始值。否则不生效。设置初始值也就是在getList()方法时进行的,设置每行的loading默认初始值是false。这是因为在请求过程中修改状态时Vue不能检测到对象属性的添加或删除,就必须先给对象添加此属性,然后再去修改。

posted @ 2021-07-07 20:07  钟小嘿  阅读(2947)  评论(0编辑  收藏  举报