有的时候需要当前页面刷新,之前的js或jq可通过一下代码进行刷新页面
location.reload();
或
window.location.reload();
也可以通过vue自带的方法刷新页面
this.$router.go(0);
但是这两种刷新页面的方法都会是页面闪烁一下,很显然不是我们想要的,推荐用下面的方法进行页面的刷新
首先在App.vue中编写如下代码
<template>
<div id="app">
<router-view v-if="isRouterAlive"></router-view>
</div>
</template>
<script>
export default {
name: 'App',
provide () { //父组件中通过provide提供变量,子组件中通过inject注入变量。
return {
reload: this.reload
}
},
data() {
return{
isRouterAlive: true //控制视图是否显示
}
},
methods: {
reload () {
this.isRouterAlive = false;
this.$nextTick(function () {
this.isRouterAlive = true;
})
}
},
}
</script>
<style lang="scss">
***
</style>
然后在需要刷新的页面编写如下代码
export default {
inject:['reload'], //注入App里的reload方法
data () {
return {
}
}
}
最后在需要刷新的时机调用this.reload()即可,因为我的业务需要,在两个页面间来回切换并传值,因为页面间已经有了状态保持,所以再跳回原来的页面时获取不到跳转前的页面传过来的值,所以我直接写在了监听url路径变化的地方
watch: {
$route() {
this.reload()
}
}
最后效果实现