VUE this.$router.push跳转页面传值不同 created 函数只调用一次 页面不刷新解决办法

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

问题:

在vue中使用 this.$router.push() 方法,如果只是传入的参数不同,会出现 url
地址变化了,但是页面没有重新请求数据,生命周期函数未调用,需要刷新一下页面才有新的数据加载。

原因:

由于 Vue 会复用相同组件, 即 /page/foo => /page/bar 或者 /page?id=1 => /page?id=2
这类链接跳转时, 原来的组件实例会被复用。因为两个路由都渲染同个组件,比起销毁再创建,复用则显得更加高效。不过,这也意味着组件的生命周期钩子不会再被调用。

解决方法:

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

被 keep-alive 缓存的组件激活时调用。

2. 监听路由的变化(会调用两次不推荐)

在页面的 watch 中,监听 $router 的变化

watch: { $route (to, from) {
 ......
} }
3. 使用VUE的 v-if 控制DOM

注意:this.$router.push 需要用 query 传参

app.vue
<template>
<!-- VUE 路由 -->
<router-view v-if="RouteState"></router-view>
</template>
<script>
export default {
  name: 'App',
  data() {
    return {
      searchText:'',
      RouteState:true,
    }
  },
  methods: {
    reload(){
      this.RouteState = false;
      this.$nextTick(()=>{
        this.RouteState = true;
      });
      this.$router.push({
        name: 'doclist',
        query: {
             keywords:this.searchText
        }
      });
    },
 }
}

4. beforeRouteUpdate 导航守卫
const User = {
  template: '...',
  beforeRouteUpdate(to, from, next) {
   this.name = to.params.name
   next()
  }
}
5. beforeRouteEnter 导航守卫
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.init()
    })
  },
6. 给router-view 绑定相应的key值

设置 router-view 的 key 属性值为 $route.path,或则为 $route.fullpath

<template>
  <section class="app-main">
    <transition name="fade-transform" mode="out-in">
      <router-view :key="key" />
    </transition>
  </section>
</template>

<script>
export default {
  name: 'AppMain',
  computed: {
    key() {
      return this.$route.fullPath
    }
  }
}
</script>

$route.path
  • 从 /page/1 => /page/2, 由于这两个路由的 $route.path 并不一样, 所以组件被强制不复用
  • 从 /page?id=1 => /page?id=2, 由于这两个路由的 $route.path 一样, 所以和没设置 key 属性一样,
    会复用组件
$route.fullPath
  • 从 /page/1 => /page/2, 由于这两个路由的 $route.fullPath 并不一样, 所以组件被强制不复用
  • 从 /page?id=1 => /page?id=2, 由于这两个路由的 $route.fullPath 并不一样, 所以组件被强制不复用
7. 跟缓存keep-alive有关
 <keep-alive :include="searchResult">
    <router-view></router-view>
  </keep-alive>
8. window 的 addEventListener 监听方式(hash 模式)
 // 检测浏览器路由改变页面不刷新问题,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()
   this.$router.push({
        path: "/homePage/searchResult",
        query: {
          keywords: this.input,
          type: this.type,
          date:new Date().getTime()
        }
      })
  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值