vue刷新当前页面,不留白

在项目中可能有需要刷新当前页面的需求
一般有这几种刷新当前页面的方法

1,history.go(0)
2,location.reload()
3,location=location
4,location.assign(location)
5,document.execCommand(‘Refresh’)
6,window.navigate(location)
7,location.replace(location)
8,document.URL=location.href

但是这几种都会出现白屏情况,用户体验很差

**

推荐解决方法:

**
用provide / inject 组合

原理:允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效

在App.vue,声明reload方法,控制router-view的显示或隐藏,从而控制页面的再次加载。

<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()调用,即可刷新当前页面。

注入reload方法

	inject::['reload']
export default {
	name:"header",
	inject::['reload'],      //重点!!!!
	data(){
		return{

		}
	}
}

调用:

this.reload()

需要注意的是this的指向

猜你喜欢

转载自blog.csdn.net/qq_43138078/article/details/91817609