vue刷新当前页面
背景
在项目开发中遇到了需要刷新当前页面的场景。中途尝试了以下四种方法
1、this.
f
o
r
c
e
U
p
d
a
t
e
(
)
t
h
i
s
.
forceUpdate() this.
forceUpdate()this.forceUpdate() 是Vue.js中的一个方法,用于强制组件重新渲染,即使没有响应式数据发生变化。
2、 this.$router.go(0)
在history记录中前进或者后退val步,当val为0时刷新当前页面。
3、location.reload()
可以简单地实现当前页面的刷新,这个方法会重新加载当前页面,类似于用户点击浏览器的刷新按钮。
4、window.location.href = window.location.href
这个方法会重新加载当前URL所对应的页面,从而实现页面的刷新效果
具体使用如下
<button @click="refresh">刷新页面</button>
methods: {
refresh() {
//以下方法任选一种
//方法1
this.$forceUpdate();
//方法2
//this.$router.go(0);
//方法3
//location.reload();
//方法4
//window.location.href = window.location.href ;
}
}
这些方法都会刷新整个页面,中间会出现明显的闪屏,体验感不是太好。
几经波折终于找到了一个之局部刷新的方法
用provide / inject 组合
原理:允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效
在App.vue,声明reload方法,控制router-view的显示或隐藏,从而控制页面的再次加载。
<template>
<div id="app">
<router-view v-if="isRouterAlive"></router-view>
</div>
</template>
<script>
export default {
name: 'App',
provide () {
return {
reload: this.reload
}
},
data () {
return {
isRouterAlive: true
}
},
methods: {
reload () {
this.isRouterAlive = false
this.$nextTick(function () {
this.isRouterAlive = true
})
}
}
}
</script>
在需要用到刷新的页面。在页面注入App.vue组件提供(provide)的 reload 依赖,在逻辑完成之后(删除或添加…),直接this.reload()调用,即可刷新当前页面。
注入reload方法
methods: {
refresh() {
//以下方法任选一种
//方法1
//this.$forceUpdate();
//方法2
//this.$router.go(0);
//方法3
//location.reload();
//方法4
//window.location.href = window.location.href ;
//方法5
this.reload();
}
}