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

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

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

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



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

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



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

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



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

   {

        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>





在需要刷新的頁(yè)面使用



refresh() {

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

      const { fullPath } = this.$route

      this.$router.replace({

        path: '/redirect' + fullPath

      })

    }



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

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



方式3:provede/inject 方式

vue官方文檔說(shuō)了,這個(gè)依賴注入方式是給插件開(kāi)發(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 '抱歉,您訪問(wèn)的頁(yè)面地址有誤或者該頁(yè)面不存在...'

    }

  },

  methods: {

  handleReload() {

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

}

  }

}

</script>



<style lang="scss" scoped>

</style>



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


分享本文至:

日歷

鏈接

個(gè)人資料

存檔