一、什么是vue中的静默刷新
静默刷新简单来说就是通过重新渲染组件(重新走一遍组件的生命周期,下面会演示)或更新组件的数据来刷新页面的局部内容,而不刷新整个页面的过程。重新触发渲染路由来实现静默刷新是一种有效的方法,特别是在 Vue.js 等前端框架中。
二、演示代码
1、APP.vue中的代码
<script setup lang="ts">
import { nextTick, provide, ref } from 'vue';
// 控制是否渲染路由视图
const isRouterAlive = ref(true);
// 重新加载路由视图
const reload = () => {
isRouterAlive.value = false;
nextTick(() => {
isRouterAlive.value = true;
});
};
// 使用 provide reload 函数提供给了整个组件树。
// 任何在这个组件树中的子组件都可以通过 inject 来访问到 reload 函数。
provide('reload', reload);
</script>
<template>
<router-view v-slot="{ Component }" v-if="isRouterAlive">
<keep-alive :include="['DemoRefresh']">
<component :is="Component"></component>
</keep-alive>
</router-view>
<!-- 不使用缓存和动态组件的方式来渲染路由的情况下,也是可以静默刷新的 -->
<!-- <router-view v-if="isRouterAlive"> </router-view> -->
</template>
<style scoped></style>
- 当调用
reload
函数时,它会将isRouterAlive
的值设置为false
,然后在下一个 DOM 更新周期中再将其设置为true
。这样可以触发重新渲染路由视图的逻辑。子组件代码如下:
DemoRefresh.vue
<template>
<div class="demo-refresh">静默刷新</div>
<div class="ipt">
<input type="text" v-model="userName" />
</div>
<button @click="refresh" class="btn">点击-静默刷新</button>
</template>
<script setup lang="ts">
import { inject, onMounted, onUnmounted, onUpdated, ref } from 'vue';
defineOptions({
name: 'DemoRefresh',
});
const reload = inject('reload');
const userName = ref('');
onMounted(() => {
console.log('onMounted');
});
onUpdated(() => {
console.log('onUpdated');
});
onUnmounted(() => {
console.log('onUnmounted');
});
const refresh = () => {
reload();
};
</script>
<style scoped>
.btn {
color: #fff;
background-color: rgba(0, 0, 0, 0.35);
}
.ipt {
margin: 20px 0;
}
</style>
2、视频看一下效果
静默刷新
三、作用
1)保持用户的流畅体验
2)降低网络带宽消耗:相比于全页面刷新或用户手动刷新,静默刷新通常只会更新部分内容,从而减少了网络带宽的消耗,提高了网络效率。
3)优化性能:静默刷新可以有选择性地更新需要更新的内容,而不是重新加载整个页面,这样可以减少服务器和客户端的工作负载,提高了应用程序的性能表现。
4)支持实时数据更新:对于需要实时更新数据的应用程序,静默刷新可以定期或根据特定事件来更新数据,确保用户可以及时看到最新的信息。