[英]How to set afterEach handler in vue-router
I have the following script: 我有以下脚本:
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
scrollBehavior (to, from, savedPosition) {
// purposely left blank
},
routes: [
{
path: "/",
component: SampleComponent
}
]
}
I would like to add an afterEach
handler to the router so that I can close any open menus when a router link is taken. 我想在路由器上添加一个
afterEach
处理程序,以便在获取路由器链接时可以关闭所有打开的菜单。
I tried to add it to the constructor but it is not a constructor argument. 我试图将其添加到构造函数中,但它不是构造函数参数。
I also tried: 我也尝试过:
Router.afterEach((to, from) => {
// ...
})
But I get an error: 但是我得到一个错误:
afterEach is not a function
afterEach不是一个函数
How do I appropriately add an afterEach
callback with this setup? 如何在此设置中适当添加
afterEach
回调?
You need to set the afterEach
handler on a Router
instance (the object returned via new Router()
). 您需要在
Router
实例(通过new Router()
返回的对象)上设置afterEach
处理程序。
You can set a reference to your instance, and add the afterEach
handler to it before it's exported: 您可以设置对实例的引用,并在
afterEach
实例之前将afterEach
处理程序添加到实例中:
const router = new Router({
scrollBehavior (to, from, savedPosition) {
// purposely left blank
},
routes: [
{
path: "/",
component: SampleComponent
}
]
});
router.afterEach((to, from) => {
// ...
});
export default router
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.