vue 使用同一组件,切换时不触发created、mounted钩子

两个页面参数不同使用同一组件,默认情况下当这两个页面切换时并不会触发created或者mounted钩子。

方法一:通过watch $route的变化来做处理

watch: {
    $route() {
      if (this.$route) {
        ...
      }
    }
},

方法二:在 router-view上加上一个唯一的key,来保证路由切换时都会重新渲染触发钩子

<router-view :key="key"></router-view>

computed: {
    key() {
        return this.$route.name !== undefined? this.$route.name + +new Date(): this.$route + +new Date()
    }
 }

猜你喜欢

转载自www.cnblogs.com/conglvse/p/10361767.html