vue刷新当前页面最好办法

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

vue刷新当前页面有挺多种方法,比如
window.location.reload()

或者
this.$router.go(0)

但是这两种方法是会出现一瞬间的白屏,体验不好,所以这里给大家推荐第三种比较好用的刷新页面的方法
在app.vue的<router-view></router-view>加上v-if属性

<router-view v-if="isRouterAlive"></router-view>
在data里面加上isRouterAlive,当然这个属性名可以自己定义,默认值为true

  data () {
      return {
        isRouterAlive: true
      }
  }
methods里面加入一个刷新的方法

methods: {
    reload () {
      this.isRouterAlive = false
      this.$nextTick(function() {
         this.isRouterAlive = true
      })
    }
  }
最后,需要把这个函数 provide 出去

provide () {
    return {
      reload: this.reload
    }
  }
这样,app.vue上就设置完了
那么当我们需要刷新的时候,在需要的页面上加上这个函数就可以了
首先注入这个函数

inject: ['reload']
然后在需要用到这个函数的地方去引用就行了

refresh () {
  this.reload()
}
这样子就可以刷新页面了,而且不会出现白屏的情况,比前面两种方法好用,推荐大家使用。
附带上完整代码
<template>
  <div id="app">
    <div class="wrap">
      <router-view v-if="isRouterAlive"></router-view>
    </div>
  </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>

<style>
  #app{
    position: relative;
  }
  @media only screen and (min-width: 1200px) {
    .wrap{
      width: 65%;
      margin: 0 auto;
    }
  }
  
</style>

<template>
    <button @click="refresh"></button>
</template>
<script>
    export default{
        name: 'refresh',
        inject: ['reload'],
        methods: {
              refresh () {
                  this.reload()
              }
        }
    }
</script>

 

posted @ 2020-09-18 10:20  ThisCall  阅读(295)  评论(0编辑  收藏  举报