Vue 刷新当前页面

方法一
window.location.reload()

方法二
this.$router.go(0)

方法一和方法二是会出现一瞬间的白屏,用户体验不好,这里推荐第三种,亲测好用

在app.vue的加上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
      })
    }
  }

app.vue的设置就是以上
当需要刷新时,在页面上加上个这个函数就可以
首先注入这个函数

inject: ['reload']

然后在需要用到这个函数的地方去引用就行了

refresh () {
  this.reload()
}

这样子就可以刷新页面了,而且不会出现白屏的情况,比前面两种方法好用,推荐大家使用。

完整代码
app.vue

<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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值