vue項(xiàng)目刷新當(dāng)前頁面的幾種方式

2019-11-4    seo達(dá)人

在vue項(xiàng)目中,經(jīng)常會遇到需要刷新當(dāng)前頁面的需求。

因?yàn)関ue-router判斷如果路由沒有變化,是不會刷新頁面獲取數(shù)據(jù)的。



方式1:go(0)和reload()

通過location.reload()或是this.$router.go(0)兩種強(qiáng)制刷新方式,相當(dāng)于按F5,會出現(xiàn)瞬間白屏,體驗(yàn)差,不推薦。



方式2:定義一個(gè)空白路由頁面,路由跳轉(zhuǎn)到該空白頁后立馬跳回當(dāng)前頁,實(shí)現(xiàn)路由刷新。

在router路由表中定義一個(gè)空白路由,



 // 強(qiáng)制刷新當(dāng)前頁所用的中間跳轉(zhuǎn)頁

   {

        path: '/redirect/:path*',

        component: () => import('@/views/redirect/index')

  }



寫一個(gè)空白路由組件



//redirect/index

<script>

export default {

  created() {

    const { params, query } = this.$route

    const { path } = params

    this.$router.replace({ path: '/' + path, query })

  },

  render: function(h) {

    return h() // avoid warning message

  }

}

</script>





在需要刷新的頁面使用



refresh() {

      // 刷新當(dāng)前路由

      const { fullPath } = this.$route

      this.$router.replace({

        path: '/redirect' + fullPath

      })

    }



這種方式,基本上能夠應(yīng)付絕大多數(shù)情況,推薦使用。

但是,有時(shí)候,有一些極端情況下,這種刷新不起作用,而又不想用第一種那種毛子般的簡單粗暴的方式的話,下面的方式可以選擇使用。



方式3:provede/inject 方式

vue官方文檔說了,這個(gè)依賴注入方式是給插件開發(fā)使用的,普通應(yīng)用中不推薦使用。

但是,效果卻很好。

app.vue修改



<template>

  <div id="app">

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

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





使用的時(shí)候:

demo.vue



<template>

  <div class="container">

  xxx

  </div>

</template>



<script>

export default {

  inject: ['reload], // 依賴注入

  name: 'Demo',

  computed: {

    message() {

      return '抱歉,您訪問的頁面地址有誤或者該頁面不存在...'

    }

  },

  methods: {

  handleReload() {

  this.reload() // 直接在需要刷新的方法中調(diào)用這個(gè)reload()

}

  }

}

</script>



<style lang="scss" scoped>

</style>



原理就是通過依賴注入的方式,在頂部app通過v-if的顯示隱藏來強(qiáng)制切換顯示,以此來讓vue重新渲染整個(gè)頁面,app中通過provide方式定義的reload方法,在它的后代組件中,無論嵌套多深,都能夠觸發(fā)調(diào)用這個(gè)方法。具體說明查看官方文檔。


分享本文至:

日歷

鏈接

個(gè)人資料

存檔