在项目中会有一些操作是需要页面刷新的,我今天就遇到了,因为组件层级过多,我总不能一级一级往上取值,再一级一级的往下赋值吧,所以我想到了刷新页面,那就简单记录一下吧!
方法一:
// Vue路由跳转
this.$router.go(0) // 类似window.history.go(n),向前或向后跳转n个页面,n可正(先后跳转)可负(向前跳转)
this.$router.replace('/path') // 跳转到指定URL,替换history栈中最后一个记录,点击后退会返回至上上一个页面
this.$router.push('/path') // 跳转到指定URL,向history栈添加一个新的记录,点击后退会返回至上一个页面
方法二:
location.reload() // 类似于F5按钮刷新
以上的两种方法会出现页面会一瞬间的白屏的问题,体验效果不是很好哦,建议使用方法三。
方法三:
使用provide
/ inject
组合
- 配对使用:provide 和 inject 需要成对使用
- 作用:祖先组件可向其所有子孙后代传递数据
- 优点:当孙组件想要访问祖先组件的 property 时,通过 provide/inject 可以轻松实现跨级访问数据
原理:允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效
1、在App.vue
,声明reload()
,控制router-view
的显示或隐藏,控制页面的再次加载。
<template>
<div id="app">
<router-view v-if="isRouterAlive" />
</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>
2、在需要用到刷新的页面。在页面注入App.vue
组件提供 provide
的 reload
依赖,就可以在你需要刷新的方法里添加 this.reload() 即可刷新当前页面。
①注入reload
方法
inject: ['reload']
②调用this.reload()