我想在已加载的路由(第一条路由)上运行一个函数,然后转到第二条路由。用户再次从第二条路线转到第一条路线。
当用户在Vue和Vuex中从第二条路线转到第一条路线时,我想在第一条路线上运行功能。
我尝试了Vue生命周期挂钩(例如Created,beforeMount),但是它们都不起作用。
能否请您告诉我我需要运行什么以及如何在Vue项目上运行它。
谢谢
答案 0 :(得分:1)
vue-router navigation guards,您可以定义全局挂钩来调用beforeEach路由器更改或afterEach。
例如pre-route guard的示例:
//router.js
const router = new VueRouter({
routes: [
{
path: '/night',
component: nightComponent,
beforeEnter: (to, from, next) => {
const currentHour = new Date().getHours();
if(currentHour < 6){
next(); // this function will trigger the routing. in my example, i
//call it only if its not morning yet.
}
}
}
]
})
您还可以定义in-component guard,以对更改此特定路线采取措施。
new Vue({
el: "#app",
router,
data: {},
methods: {},
beforeRouteLeave (to, from, next) {
// called when the route that renders this component is about to
// be navigated away from.
// has access to `this` component instance.
if(confirm('are you sure you want to leave this page?')){
next();
}
}
}
})