先上效果圖:

說明:在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不能檢測到對象屬性的添加或刪除,就必須先給對象添加此屬性,然后再去修改。
