Vue中实现页面刷新的几种方式
1.原页面刷新,类似于F5
this.$router.go(0)
或者
location.reload()
2.创建一个空白页面(blank.vue),通过路由的方式先跳转到空白页面再跳转回来
this.$router.replace({ path:’/blank’ })
3.使用inject / provide组合控制显示
方法1和2的刷新是比较传统的动态刷新,整个页面会出现停顿和白屏,体验感不好。
推荐使用方法3,类似于静态刷新。
(1)添加:provide
1)在路由容器(一般是在App.vue 页面中)router-view添加:v-if=”isRouterAlive”
1 | <keep-alive> |
2)在data函数中添加:isRouterAlive: true,
1 | data() { |
3)添加一个provide类型,内容如下:
1
2
3
4
5 provide() {
return {
reload: this.reload,
};
},
4)在method方法中添加以下内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 reload() {
this.isRouterAlive = false; //先关闭,
this.$nextTick(function () {
console.log('inject');
this.isRouterAlive = true; //再打开
});
},
```
(2)引用:inject
在需要刷新的页面注入inject
{% blockquote %}
inject: ["reload"]
this.reload();
{% endblockquote %}
使用范例:
```bash
export default {
inject: ["reload"],
beforeCreate() {
window.setTimeout(() => {
this.orderlist1 = JSON.parse(sessionStorage.getItem("orderlist1"));
this.orderlist2 = JSON.parse(sessionStorage.getItem("orderlist2"));
this.showinfo();
}, 500);
},
created() {
setTimeout(() => {
this.reload();
}, 2000);
}
}
这里做了一个延迟刷新,因为是静态的,为了验证是否起到作用,可以在relolad()方法中打印有一些标识信息;