vue刷新当前页

79 篇文章 0 订阅
59 篇文章 1 订阅

在我们开发vue项目的时候经常会遇到需要刷新当前页的情况

遇到这种我们首先可能会想到路由跳转到当前页

this.$router.replace({
	path: '当前页在router里配置的路径',
	name: '当前页在router里配置的name'
})

但是使用这种方式跳转页面后,页面内显示的数据是不进行更新的,所以这种方法是不可行的

解决方法:

1、使用 location.reload() 或者 this.$router.go(0)

//方法1:
location.reload()
//方法2:
this.$router.go(0)

缺点:当使用ctrl+F5 这种强制刷新,整个页面重新加载,会出现一个瞬间的空白页面

2、新建一个页面,当要刷新时用使用this.$router.replace()方法先跳转到新页面再跳转回这一页的方法来代替刷新

需要刷新的页面:

this.$router.replace({
	path: '新页面在router里配置的路径',
	name: '新页面在router里配置的name'
})

新页面:

this.$router.replace({
	path: '需要刷新的页面在router里配置的路径',
	name: '需要刷新的页面在router里配置的name'
})

3、provide / inject 组合方法

(1)修改app.vue

<template>
  <div id="app">
    <router-view v-if="isRouterAlive"/>
  </div>
</template>

<script>
export default {
  name:'app',
  data(){
   return{
     isRouterAlive: true
   }
  },
  provide(){
    return{
      reload:this.reload
    }
  },
  methods:{
    reload(){
      this.isRouterAlive = false
      this.$nextTick(function(){
        this.isRouterAlive = true
      })
    }
  }
}
</script>

(2)在当前需要刷新的页面进行依赖的注入然后就可以使用啦

<script>
export default {

//1、注入App.vue组件提供(provide)的 reload 依赖
  inject:['reload'],

  name:'...',
  
  data(){...},
  
  methods:{
  //2、然后在方法中调用this.reload()就可以啦
    refresh(){
      this.reload()
    }
  }
}
</script>

以上就是vue项目中进行页面刷新的三种方法。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值