返回
在 Table 中巧用 v-loading,数据加载时优雅地呈现“Loading”
前端
2023-09-24 16:01:03
在日常开发中,我们经常会遇到需要在页面上显示表格数据的情况。为了让用户在数据加载过程中获得更好的体验,我们可以使用 Vue.js 的 v-loading 指令来显示一个加载中的指示器。
使用 v-loading 指令
要使用 v-loading 指令,首先需要在 Vue.js 项目中安装相应的库。您可以使用以下命令进行安装:
npm install vue-loading-overlay --save
安装完成后,您可以在 Vue.js 组件中使用 v-loading 指令。指令的使用方法如下:
<template>
<div>
<table v-loading="isLoading">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.name }}</td>
<td>{{ user.age }}</td>
<td>{{ user.gender }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import Vue from 'vue'
import VueLoading from 'vue-loading-overlay'
import 'vue-loading-overlay/dist/vue-loading.min.css'
Vue.use(VueLoading)
export default {
data() {
return {
isLoading: true,
users: []
}
},
created() {
// 模拟异步数据请求
setTimeout(() => {
this.users = [
{ id: 1, name: '张三', age: 20, gender: '男' },
{ id: 2, name: '李四', age: 25, gender: '女' },
{ id: 3, name: '王五', age: 30, gender: '男' }
]
this.isLoading = false
}, 1000)
}
}
</script>
在这个例子中,我们使用了 Vue.js 的 v-loading 指令来在 table 表格上显示一个加载中的指示器。当 isLoading 为 true 时,加载中的指示器会显示,当 isLoading 为 false 时,加载中的指示器会消失。
自定义加载中的指示器
您可以自定义加载中的指示器。例如,您可以使用以下代码来创建一个自定义的加载中的指示器:
<template>
<div>
<div v-if="isLoading" class="loading">
<div class="loading-icon"></div>
<span class="loading-text">Loading...</span>
</div>
<table v-else>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.name }}</td>
<td>{{ user.age }}</td>
<td>{{ user.gender }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import Vue from 'vue'
import VueLoading from 'vue-loading-overlay'
import 'vue-loading-overlay/dist/vue-loading.min.css'
Vue.use(VueLoading)
export default {
data() {
return {
isLoading: true,
users: []
}
},
created() {
// 模拟异步数据请求
setTimeout(() => {
this.users = [
{ id: 1, name: '张三', age: 20, gender: '男' },
{ id: 2, name: '李四', age: 25, gender: '女' },
{ id: 3, name: '王五', age: 30, gender: '男' }
]
this.isLoading = false
}, 1000)
}
}
</script>
<style>
.loading {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
}
.loading-icon {
width: 50px;
height: 50px;
border-radius: 50%;
border: 5px solid #fff;
border-top-color: #f39c12;
animation: loading-icon 1s linear infinite;
}
.loading-text {
color: #fff;
font-size: 16px;
margin-left: 10px;
}
@keyframes loading-icon {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
在这个例子中,我们使用了一个自定义的加载中的指示器。这个加载中的指示器是一个圆形的进度条,并在圆形进度条旁边显示“Loading...”的文字。
总结
使用 v-loading 指令可以在 Vue.js 中轻松地实现数据加载时的加载中效果。您可以使用默认的加载中的指示器,也可以自定义加载中的指示器。