vue实现页面刷新动画
在web应用程序中,页面的刷新是一件常见的事情。但是通常情况下,用户点击刷新按钮之后,页面回到了最开始的状态,这种刷新方式可能不太友好。为了提供更好的用户体验,我们可以添加一些动画效果来展示页面刷新的过程。本文将介绍如何使用Vue实现一个简单的页面刷新动画。
实现思路
我们的目标是创建一个通用的组件,该组件将取代默认的页面刷新行为。以常见的下拉刷新为例,用户下拉页面时触发刷新,此时页面底部将展示一个刷新loading图标,当页面完成刷新后,loading图标会消失。
由于我们需要实时监听页面刷新事件,因此需要在Vue的生命周期中添加监听事件。在监听到刷新事件后,让UI做出相应的改变,展示loading图标。
首先,在Vue的created生命周期函数中创建一个事件监听器:
created() {
window.addEventListener('beforeunload', this.showRefreshIndicator)
}
然后,定义showRefreshIndicator()函数,在其中启用刷新loading图标。
showRefreshIndicator() {
this.refreshing = true // refreshing是状态变量
}
refreshing变量将控制loading图标是否展示。下一步,我们需要在模板中添加loading图标。由于这是通用组件,因此我们可以将这个组件复用在多个页面上。因此,建议将loading图标的模板独立出来,在组件中引入。
<template>
<div>
<slot></slot>
<div v-if="refreshing" class="refresh-indicator"><i class="icon-refresh"/></div>
</div>
</template>
最后,当页面刷新完成时,我们需要将loading图标从页面中移除。我们可以监听window的load事件,并在事件发生时,将refreshing变量设置为false。
window.addEventListener('load', () => {
this.refreshing = false
})
完整代码实例
下面是一个完整的实现示例,我们将使用Vuetify UI框架来实现loading图标的样式。
<template>
<v-container>
<v-layout row wrap justify-center>
<v-flex xs12>
<v-card flat>
<v-card-text>
<h1>我是一个页面示例</h1>
<p>以下是页面内容</p>
<slot></slot>
<div v-if="refreshing" class="refresh-indicator"><i class="mdi mdi-refresh mdi-spin"/></div>
</v-card-text>
</v-card>
</v-flex>
</v-layout>
</v-container>
</template>
<script>
export default {
data () {
return {
refreshing: false
}
},
created () {
window.addEventListener('beforeunload', this.showRefreshIndicator)
window.addEventListener('load', () => {
this.refreshing = false
})
},
methods: {
showRefreshIndicator () {
this.refreshing = true
}
}
}
</script>
<style>
.refresh-indicator {
position: fixed;
bottom: 0;
width: 100%;
height: 40px;
background-color: #fff;
text-align: center;
z-index: 9999;
border-top: 1px solid #ddd;
display: flex;
justify-content: center;
align-items: center;
}
</style>
参考
- https://codepen.io/Gigacore/pen/PbZegE
- https://stackoverflow.com/questions/23994242/call-function-before-page-reload-javascript
