console
const Home = { template: '<div>home</div>' }
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
function guardRoute (to, from, next) {
if (window.confirm(`您确定要导航至 ${to.path}?`)) {
next()
} else if (window.confirm(`您确定要重定向到 /baz?`)) {
next('/baz')
} else {
next(false)
}
}
const Baz = {
data () {
return { saved: false }
},
template: `
<div>
<p>baz ({{ saved ? '已保存' : '未保存' }})<p>
<button @click="saved = true">保存</button>
</div>
`,
beforeRouteLeave (to, from, next) {
if (this.saved || window.confirm('数据未保存,你是否要离开?')) {
next()
} else {
next(false)
}
}
}
const Qux = {
data () {
return {
msg: null
}
},
template: `<div>{{ msg }}</div>`,
beforeRouteEnter (to, from, next) {
setTimeout(() => {
next(vm => {
vm.msg = 'Qux'
})
}, 2000)
}
}
const Quux = {
data () {
return {
prevId: 0
}
},
template: `<div>id:{{ $route.params.id }} prevId:{{ prevId }}</div>`,
beforeRouteUpdate (to, from, next) {
this.prevId = from.params.id
next()
}
}
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/', component: Home },
{ path: '/foo', component: Foo, beforeEnter: guardRoute },
{ path: '/bar', component: Bar, meta: { needGuard: true }},
{ path: '/baz', component: Baz },
{ path: '/qux', component: Qux },
{ path: '/qux-async', component: resolve => {
setTimeout(() => {
resolve(Qux)
}, 0)
} },
{ path: '/quux/:id', component: Quux }
]
})
router.beforeEach((to, from, next) => {
if (to.matched.some(m => m.meta.needGuard)) {
guardRoute(to, from, next)
} else {
next()
}
})
new Vue({
router,
el:'#app'
}).$mount('#app')
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vue-router/3.1.6/vue-router.js"></script>
<div id="app">
<h1>导航钩子</h1>
<ul>
<li><router-link to="/">/</router-link></li>
<li><router-link to="/foo">/foo</router-link></li>
<li><router-link to="/bar">/bar</router-link></li>
<li><router-link to="/baz">/baz</router-link></li>
<li><router-link to="/qux">/qux</router-link></li>
<li><router-link to="/qux-async">/qux-async</router-link></li>
<li><router-link to="/quux/1">/quux/1</router-link></li>
<li><router-link to="/quux/2">/quux/2</router-link></li>
</ul>
<router-view class="view"></router-view>
</div>