钩子:vue组件中的“beforeRouteEnter”将被触发的条件是什么?

时间:2017-08-31 08:56:45

标签: vuejs2 hook vue-router

我是Vue.js的新手,在学习导航保护挂钩时遇到了一些问题。 我为Foo组件和Home组件设置了组件钩子:'beforeRouteEnter'。当浏览器转到'/'时,它将重定向到'/ home',而Foo是Home的默认子组件,因此它将被渲染,并触发foo组件钩子。我知道以上所有内容,我想知道的是:

  • 当路由从'/ home'变为'/ home / foo'时,foo组件是 确实重用了,为什么Foo组件的钩子会被触发?
  • 当路由从'/ home / foo'变为'/ home'时,Foo的钩子 组件将被触发,但主组件也被重用,为什么 Home组件的钩子没有被触发?

请参阅fiddle demo

<!-- 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
    }) 

0 个答案:

没有答案