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