vue项目刷新当前页面的几种方式

2019-11-4    seo达人

在vue项目中,经常会遇到需要刷新当前页面的需求。

因为vue-router判断如果路由没有变化,是不会刷新页面获取数据的。



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

通过location.reload()或是this.$router.go(0)两种强制刷新方式,相当于按F5,会出现瞬间白屏,体验差,不推荐。



方式2:定义一个空白路由页面,路由跳转到该空白页后立马跳回当前页,实现路由刷新。

在router路由表中定义一个空白路由,



 // 强制刷新当前页所用的中间跳转页

   {

        path: '/redirect/:path*',

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

  }



写一个空白路由组件



//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() {

      // 刷新当前路由

      const { fullPath } = this.$route

      this.$router.replace({

        path: '/redirect' + fullPath

      })

    }



这种方式,基本上能够应付绝大多数情况,推荐使用。

但是,有时候,有一些极端情况下,这种刷新不起作用,而又不想用第一种那种毛子般的简单粗暴的方式的话,下面的方式可以选择使用。



方式3:provede/inject 方式

vue官方文档说了,这个依赖注入方式是给插件开发使用的,普通应用中不推荐使用。

但是,效果却很好。

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>





使用的时候:

demo.vue



<template>

  <div class="container">

  xxx

  </div>

</template>



<script>

export default {

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

  name: 'Demo',

  computed: {

    message() {

      return '抱歉,您访问的页面地址有误或者该页面不存在...'

    }

  },

  methods: {

  handleReload() {

  this.reload() // 直接在需要刷新的方法中调用这个reload()

}

  }

}

</script>



<style lang="scss" scoped>

</style>



原理就是通过依赖注入的方式,在顶部app通过v-if的显示隐藏来强制切换显示,以此来让vue重新渲染整个页面,app中通过provide方式定义的reload方法,在它的后代组件中,无论嵌套多深,都能够触发调用这个方法。具体说明查看官方文档。


分享本文至:

日历

链接

blogger

蓝蓝 http://www.lanlanwork.com

存档