导读: 在vue-router中,在当前页面中点击当前页面的路由,页面是不会进行刷新的,如何做到点击当前页面并进行刷新呢?
1. 解决方法:
this.$router.go(0);location.reload()
2. 存在的问题
上两种方法 都会出现闪屏的问题 影响用户体验。如何做到页面刷新不闪屏呢?
想法:用一个空页面做中转,空白页面再跳转回来,解决了闪屏的问题,但如果用户点击返回上一页便会出现问题,也不行
3. 推荐方案:
- 在App.vue,声明reload方法,控制router-view的显示或隐藏,从而控制页面的再次加载。(provide /inject )
- 祖先组件(provide )会向其所有子孙后代(inject )注入一个依赖
<template>
<div id="app">
<router-view v-if="routerState" />
</div>
</template>
<script>
export default {
name: 'BasiC',
provide() {
return {
reload: this.reload
}
},
//声明变量
data() {
return {
routerState: true
}
},
methods: {
//利用$nextTick特性,router跳转完成后展示页面
reload() {
this.routerState = false;
this.$nextTick(() => {
this.routerState = true;
})
}
}
}
</script>
- 在需要的页面调用方法
inject: ["reload"],
methods: {
itemClick(item) {
if (item.path === '/main/sparepart') {
this.$router.push(item.path)
} else {
console.log(item)
this.$router.push({
path: "/about",
query: item
})
this.reload();
}
}
},
4. 新增一种解决方法
使用key的唯一性来重置router-view
使用场景:创建和编辑的页面使用的是同一个component,需要重新调用生命周期函数重新载入数据
<router-view :key="key"></router-view>
computed: {
key() { return this.$route.name !== undefined ? this.$route.name + +new Date() : this.$route + +new Date() }
}