开发vue项目时,框架需要一个刷新按钮,手动刷新页面渲染,我们知道window.reload(),或者router.go(0)可以路由刷新,重新进入当前页面,但是这种方法的问题在于会导致页面白屏,用户体验不是很好。
provide、inject方式
我们在需要刷新的路由层级,<router-view>
渲染的地方用v-if去控制页面刷新。在这里用App.vue举例
<template>
<div id="app">
<router-view v-if="isRouterAlive"></router-view>
</div>
</template>
<script>
export default {
name: "App",
// 父组件中通过provide来提供变量,在子组件中通过inject来注入变量。
provide() {
return {
reload: this.reload,
};
},
data() {
return {
// 控制视图是否显示的变量
isRouterAlive: true,
};
},
methods: {
reload() {
//先关闭,再打开
this.isRouterAlive = false;
this.$nextTick(function () {
this.isRouterAlive = true;
});
},
},
};
</script>
子组件<header-bar>
接收reload方法,并在点击刷新的时候调用,这样就实现了整个页面的刷新效果
export default {
name: "HeaderBar",
inject: ["reload"],
methods: {
...mapActions(["handleLogOut"]),
handleCollpasedChange(state) {
this.$emit("on-coll-change", state);
},
handleRefresh() {
this.reload();
},
}