当用户在 Vue 和 Vuex 中从第 1 条路线转到第 2 条路线,第 2 条路线转到第 1 条路线时,想要 运行 在第 1 条路线上发挥作用

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

我想运行在加载的路线(第一条路线)上执行一个功能,然后转到第二条路线。用户再次从第二条路线转到第一条路线。

我想 运行 当用户在 Vue 和 Vuex 中从第二条路线转到第一条路线时,第一条路线上的一个功能。

我尝试了像 Created、beforeMount 这样的 Vue 生命周期钩子,但是 none 可以正常工作。

你能告诉我我需要成为什么 运行 以及在 Vue 项目中如何 运行 吗?

谢谢

vue 路由器 navigation guards you can define global hooks to invoke beforeEach router change or afterEach

例如,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.
        }
      }
    }
  ]
})

您还可以定义一个 in-component guard,以对该特定路线的更改采取行动。

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();
        }
      }
   }
})