vue this.$router.push 页面不刷新总结(8种解决方式----覆盖所有场景)

这其实是一个很常见的问题,当使用push的时候,会向 history 栈添加一个新的记录,这个时候,再次添加一个完全相同的路由的时候,就不会再次刷新了.

没有耐心的可以直接看第九种方式,绝绝子,适用所有场景.

解决办法有这么几种:

1. 添加activated函数。

	activated(){
	在这里插入代码片
	}

2. 通过路由监听的方法。将mounted下的方法函数放到watch路由下

// 不推荐、用户体验不好
watch: {
	'$route' (to, from) {
    // 路由发生变化页面刷新
	this.$router.go(0);
		}
},
// 该方法会多一次请求
watch: {
	'$route' (to, from) {
    // 在mounted函数执行的方法,放到该处
	this.getTableData();
	}
},

3. 使用VUE的v-if控制DOM

注意:this.$router.push使用的是query不是params

<script>
export default {
  name: 'App',
  data() {
    return {
      msg: 'Welcome to Your Vue.js App',
      searchText:'',
      RouteState:true,
    }
  },
  methods: {
    reload(){
      this.RouteState = false;
      this.$nextTick(()=>{
        this.RouteState = true;
      });
      this.$router.push({
        name: 'doclist',
        query: {
             keywords:this.searchText
        }
      });
    },
 }
}

4. 使用beforeRouteUpdate

  beforeRouteUpdate (to, from, next) {
	  this.lang = to.params.lang;
	  this.setCode();
	  next();
	}

5. 通过组件导航守卫来设置对应的meta 属性

 beforeRouteEnter: (to, from, next) = > { // 写在当前组件
 to.meta.keepAlive = false 
 next()
},
 beforeRouteLeave: (to, from, next) = > { //写在前一个组件
 to.meta.keepAlive = false
 next()
}

正常以上几种方式就会有效,但是有的时候也会有一些特殊的情况:

6. 在router-view上添加 :key="$route.fullPath"属性即可。

	 <router-view :key="$route.fullPath" />

7. 跟缓存keep-alive有关

//添加exclude和 :key="$route.fullPath"
	<keep-alive exclude="searchResult">
      <router-view :key="$route.fullPath"></router-view>
    </keep-alive>

8.window的addEventListener监听方式

	 // 检测浏览器路由改变页面不刷新问题,hash模式的工作原理是hashchange事件
    window.addEventListener('hashchange', () => {
      let currentPath = window.location.hash.slice(1)
      if (this.$route.path !== currentPath) {
        this.$router.push(currentPath)
      }
    }, false)

9.添加date:new Date().getTime()

tip: 一个贼狗的方式,只需要一行代码,而且适用各种场景

	 this.$router.push({
        path: "/homePage/searchResult",
        query: {
          keywords: this.input,
          type: this.type,
          date:new Date().getTime()
        }
      })
  • 43
    点赞
  • 124
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 19
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

echo忘川

谢谢老板们

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值