当在vue项目中需要刷新当前页时,第一个是不是想到this.$router.push(当前页面的路径)?
但是你会发现,这样并没有什么用。因为基于vue这个框架,它发现当前路由没有改变,它并不会刷新。
解决方法1
this.$router.go(0)
或者
window.location.href()
这两种方式本质上就是重新刷新了整个页面而且随着项目业务的复杂程度,很可能会增加一些别的初始化请求,所以这并不是最优解。
解决方法2
思路是新增一个空白页,当需要执行刷新先跳转到空白页,再快速跳转回来。
实现起来很简单,我就不贴上代码了。
解决方法3
这个方法最方便快捷,连空白页的组件也不需要写。
这里用到了vue框架的provide和inject
在父组件中注入以来provide一个对象,在子组件中inject。
1、在APP.vue 页面加一个条件渲染,默认为true
<template> <div id="app"> <router-view v-if="noRefresh" /> </div></template><script>export default { name: 'App', provide() { return { reload: this.reload } }, data() { return { noRefresh: true } }, methods:{ // 需要reload时先将页面隐藏,在dom更新后的回调再将页面显示 reload() { this.noRefresh = false this.$nextTick(function(){ this.noRefresh = true }) } }}</script>
子组件
<script>export default { inject:['reload'], methods:{ func(){ //刷新时执行的函数 this.reload() } }}</script>