vue刷新當(dāng)前頁面

vue刷新當(dāng)前頁面有挺多種方法,比如

window.location.reload()

或者

this.$router.go(0)

但是這兩種方法是會出現(xiàn)一瞬間的白屏,體驗不好,所以這里給大家推薦第三種比較好用的刷新頁面的方法

在app.vue的<router-view></router-view>加上v-if屬性

<router-view v-if="isRouterAlive"></router-view>

在data里面加上isRouterAlive,當(dāng)然這個屬性名可以自己定義,默認(rèn)值為true

  data () {
      return {
        isRouterAlive: true
      }
  }

methods里面加入一個刷新的方法

methods: {
    reload () {
      this.isRouterAlive = false
      this.$nextTick(function() {
         this.isRouterAlive = true
      })
    }
  }

最后,需要把這個函數(shù) provide 出去

provide () {
    return {
      reload: this.reload
    }
  }

這樣,app.vue上就設(shè)置完了

那么當(dāng)我們需要刷新的時候,在需要的頁面上加上這個函數(shù)就可以了

首先注入這個函數(shù)

inject: ['reload']

然后在需要用到這個函數(shù)的地方去引用就行了

refresh () {
  this.reload()
}

這樣子就可以刷新頁面了,而且不會出現(xiàn)白屏的情況,比前面兩種方法好用,推薦大家使用。

附帶上完整代碼

<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>

感謝大家看完,覺得有用的可以點(diǎn)一下喜歡,蟹蟹蟹蟹

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容