# router-view复用组件生命周期钩子不执行?

路由从/user/1 => /user/2, 生命周期的created mounted等都不执行了,如果在这些钩子去做数据更新,那这样做了跳转之后,会发现数据没变,怎么解决?

# watch $route

watch: {
    $route: {
      immediate: true,
      handler() {
        console.log('watch');
        this.userId = this.$route.params.userId;
      }
    }
  }
1
2
3
4
5
6
7
8
9

# vue-router组件内的守卫beforeRouteUpdate

export default {
    beforeRouteUpdate(to, from, next) {
        console.log('beforeRouteUpdate');
        console.log(`this.$route === from: ${this.$route === from}`); // true
        this.userId = to.params.userId;
        next();
    },
    created() {
        console.log('created');
        this.userId = this.$route.params.userId;
  },
}
1
2
3
4
5
6
7
8
9
10
11
12

可以参考beforeRouteUpdate的官方解释

这么写的话,总结出两种情况相关钩子执行情况:

  • 其他页面 => /user/1

created => mounted

  • /user/1 => /user/2

只执行beforeRouteUpdate,而且这时候this.$route就是from, 要获取数据要从to获取!

oh, 这样子貌似比较麻烦,更新数据的地方得在两个地方都写, 看最后一种!

# 指定router-link的key

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

这样子写就一劳永逸了,组件复用的时候,例如/user/1 => /user/2, 由于这两个路由的$route.fullPath并不一样, 所以组件被强制不复用, 相关钩子加载顺序为: beforeRouteUpdate => created => mounted

上次更新: 2020-02-28 02:55:43