programing

사용자가 Vue 및 Vuex에서 첫 번째 경로에서 두 번째 경로 및 두 번째 경로에서 첫 번째 경로로 이동할 때 첫 번째 경로에서 기능을 실행하려고 합니다.

showcode 2023. 6. 19. 21:48
반응형

사용자가 Vue 및 Vuex에서 첫 번째 경로에서 두 번째 경로 및 두 번째 경로에서 첫 번째 경로로 이동할 때 첫 번째 경로에서 기능을 실행하려고 합니다.

적재된 경로(첫 번째 경로)에서 함수를 실행한 후 두 번째 경로로 이동하고 싶습니다.다시 사용자는 2번째 경로에서 1번째 경로로 이동합니다.

나는 사용자가 Vue와 Vuex에서 2번째 경로에서 1번째 경로로 이동할 때 1번째 경로에서 기능을 실행하고 싶습니다.

마운트 전에 Created와 같은 Vue 수명 주기 후크를 사용해 보았지만 작동하지 않습니다.

제가 Vue 프로젝트에서 무엇을 실행해야 하는지, 어떻게 실행해야 하는지 알려주실 수 있나요?

감사해요.

vue-router 탐색 가드는 각 라우터가 변경되기 전 또는 각 라우터 이후에 호출할 전역 후크를 정의할 수 있습니다.

예를 들어, 사전 경로 가드의 예:

//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.
        }
      }
    }
  ]
})

또한 구성 요소 내 가드를 정의하여 이 특정 경로 변경 시 조치를 취할 수 있습니다.

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

언급URL : https://stackoverflow.com/questions/55076384/want-to-run-function-on-1st-route-when-user-will-go-from-1st-route-to-2nd-and-2n

반응형