vue中刷新页面

当我们页面中有数据发生变化或者进行了某些操作的时候,需要将变化后的结果展示,也就是刷新页面,像F5这种刷新会导致页面闪烁,还有 window.reload(),或者router.go(0)刷新时也是,用户体验很差,所以我们需要一种页面不抖动的刷新方式

解决办法:

第一种适合大多数情况

在App.vue中声明一个reload方法

<template>
  <div id="app">
		<router-view v-if="isRouterAlive"></router-view>
  </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>

在你需要刷新的页面注入App.vue组件提供(provide)的 reload 依赖

在需要的地方使用this.reload()调用

有一点千万要注意,不要在生命周期中调用,会陷入死循环

刷新之后进入页面,执行生命周期函数再次调用又刷新了,导致页面一直在刷新

第二种

如果是类似页面中表格展示数据这种,当数据发生变化可直接再次发送请求刷新页面,而且这种刷新并不会让页面返回到第一页(如果有分页功能的话),如果是数据变化需要刷新页面,这种可能会好些

原文地址:https://www.cnblogs.com/kingjordan/p/12026979.html