美文网首页
vue刷新当前页面

vue刷新当前页面

作者: 尤雨溪的大迷弟 | 来源:发表于2020-01-07 16:16 被阅读0次

方法一:- this.$router.go(0)
        - window.location.href
        - window.location.reload()

强制刷新当前页面,浏览器进行重新加载,出现页面闪烁和空白,用户体验极差。

方法二:借助vue的API:provide/inject
在顶层路由页面定义并向子孙后代注入依赖:

<template>
  <div> 
    <router-view v-if="showFlag"></router-view> 
  </div>
</template>
<script> 
export default {
  name: 'home',
  data() {
    return {
      showFlag: true, // 控制router-view的显示或隐藏
    }
  },
  methods: { 
    reload () {
      this.isShow = false; // 先隐藏
      this.$nextTick(() => {  // $nextTick() 将回调延迟到下次 DOM 更新循环之后执行
        this.showFlag= true;
      })
    }
  },
  provide () { // 提供可注入子组件属性
    return {
      reload: this.reload
    }
  },
}

</script>

在需要刷新的组件或页面调用该方法:

export default {
  // 接收注入的数据
  inject: [
    'reload'
  ],
  methods: {
    showRouter () {
      // 调用reload方法,刷新整个页面
      this.reload()
    }
  }
}

相关文章