vue刷新当前页面

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>

感谢大家看完,觉得有用的可以点一下喜欢,蟹蟹蟹蟹

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。