vue 刷新当前页面的方法

遇到一个页面刷新的问题,记录一下

1、this.$router.go(0)

这种方法页面会一瞬间的白屏,体验不是很好,虽然只是一行代码的事

2、location.reload()

这种也是一样,画面一闪,效果总不是很好

3、跳转空白页再跳回原页面

在需要页面刷新的地方写上:this.$router.push('/emptyPage'),跳转到一个空白页。在emptyPage.vue里beforeRouteEnter 钩子里控制页面跳转,从而达到刷新的效果

beforeRouteEnter (to, from, next) {
      next(vm => {
        vm.$router.replace(from.path)
      })
}。

这种画面虽不会一闪,但是能看见路由快速变化。

4、控制<router-view>的显示隐藏

默认<router-view v-if="isRouterAlive" />isRouterAlive肯定是true,在需要刷新的时候把这个值设为false,接着再重新设为true:

this.isRouterAlive = false
this.$nextTick(function () {
  this.isRouterAlive = true
}这种方法从画面上是看不出破绽的。也可以搭配provide、inject使用。例如:<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>
然后在需要刷新的页面引入依赖:inject: ['reload'],
在需要执行的地方直接调用方法即可:this.reload()。

第4种方法的详细步骤参考该链接:https://www.jianshu.com/p/b6d7db35b6e4

参考链接如下:

https://www.cnblogs.com/qingqinglanlan/p/10131284.html

https://www.jianshu.com/p/b6d7db35b6e4

猜你喜欢

转载自www.cnblogs.com/-ting/p/12539154.html