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> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM