programing

vue 구성 요소의 "BeforeRouteEnter" 후크가 트리거되는 조건은?

prostudy 2022. 3. 19. 12:47
반응형

vue 구성 요소의 "BeforeRouteEnter" 후크가 트리거되는 조건은?

나는 Vue.js를 처음 접하고, 내비게이션 가드 훅을 배울 때 몇 가지 문제를 만났다.Foo 구성 요소 및 Home 구성 요소에 대해 'BeforeRouteEnter' 구성 요소 후크를 설정하십시오.브라우저가 '/'로 이동하면 '/home'으로 리디렉션되며, Foo는 Home의 기본 하위 구성 요소인 만큼 렌더링되고 foo 구성 요소 후크가 트리거된다. 위의 내용을 모두 알고 있으며, 내가 알고 싶은 것은 다음과 같다.

  • '/home'에서 '/home/foo'로 경로를 변경할 때 Foo 구성 요소가 다시 사용되는데, Foo 구성 요소의 후크가 트리거되는 이유는?
  • '/home/foo'에서 '/home'으로 경로를 변경할 때 Foo 구성 요소에 대한 후크가 트리거되지만 Home 구성 요소도 다시 사용되는데, Home 구성 요소에 대한 후크가 트리거되지 않는 이유는?

바이올린 데모를 참조하십시오.

<!-- html-->    
<script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/vue-router"></script>
    <div id="demo">
      <router-link to="/home">Home</router-link>
      <router-view></router-view>
    </div>

//JS    
const Home = {
        template: `
      <div>
        <p>I am home component</p>
        <router-link to="/home/foo">Foo</router-link>
        <router-view></router-view>
      </div>
      `,
      beforeRouteEnter(to, from, next) {
        alert('enter home component from ' + from.path + ' to ' + to.path)
        next()
      }
    }
    const Foo = {
        template: `
      <div>
        <p>I am foo component</p>
      </div>
      `,
      beforeRouteEnter(to, from, next) {
        alert('enter foo component from ' + from.path + ' to ' + to.path)
        next()
      }
    }

    const routes = [
        {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        component: Home,
        children: [
            {
            path: 'foo',
            component: Foo
          },
          {
            path: '',
            component: Foo
          }
        ]
      }
    ]

    const router = new VueRouter({
        routes
    })

    new Vue({
        el: "#demo",
      router
    }) 

참조URL: https://stackoverflow.com/questions/45977362/whats-the-condition-that-the-hook-beforerouteenter-in-vue-component-will-be

반응형