Home » vue » Vuejs hooks are not called on redirecting same component

Vuejs hooks are not called on redirecting same component

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have to page in Vuejs project. Both of them is on same level and have common component. When I redirect from post/new to post/edit/:id beforeMount method is not called.

redirect() {
    this.$router.push({path: `home/post/edit/${this.post.id}`})
  },

Routes:

 {
      path: 'home',
      name: 'home',
      component: {
        render(c) {
          return c('router-view')
        }
      },
      children: [  
        {
          path: 'post/new',
          component: PostForm,
          name: 'Create',
          props: {readOnly: false}
        },
        {
          path: 'post/edit/:id',
          component: PostForm,
          name: 'Edit',
          props: {readOnly: false}
        },

      ]
    },
Answers:

The instance of PostForm is reused for performance reasons. That is why beforeMount is called only once.

You should move your code to:

beforeRouteUpdate (to, from, next) {
    // the code you currently have in beforeMount
}

See https://router.vuejs.org/guide/essentials/dynamic-matching.html#reacting-to-params-changes as Jbluehdorn suggested.

###

you are using same component so visiting post/new , your component is already mounted redirecting post/edit/:id only routes are changing, try adding beforeRouteUpdate or you can also added watch on $route

watch : { $route: { immediate: true, handler() { } } }