Vick Sain
Vick Sain

Reputation: 153

Want to run function on 1st route when user will go from 1st route to 2nd and 2nd to 1st route in Vue and Vuex

I want to run a function on the loaded route (1st route) and then go to the 2nd route. Again user goes from 2nd route to 1st route.

I want to run a function on the 1st route when the user goes from 2nd route to 1st route in Vue and Vuex.

I tried Vue lifecycle hooks like Created, beforeMount but none of them is working.

Can you please tell me what should I need to be run and how it will be run on the Vue project.

Thanks

Upvotes: 1

Views: 843

Answers (1)

Efrat Levitan
Efrat Levitan

Reputation: 5612

vue-router navigation guards you can define global hooks to invoke beforeEach router change or afterEach.

for instance, an example for a pre-route guard:

//router.js

const router = new VueRouter({
  routes: [
    {
      path: '/night',
      component: nightComponent,
      beforeEnter: (to, from, next) => {
        const currentHour = new Date().getHours();
        if(currentHour < 6){
            next(); // this function will trigger the routing. in my example, i 
                   //call it only if its not morning yet.
        }
      }
    }
  ]
})

you can also define an in-component guard, to take action on change of this particular route.

new Vue({
  el: "#app",
  router,
  data: {},
  methods: {},
  beforeRouteLeave (to, from, next) {
    // called when the route that renders this component is about to
    // be navigated away from.
    // has access to `this` component instance.
       if(confirm('are you sure you want to leave this page?')){
           next();
        }
      }
   }
})

Upvotes: 1

Related Questions