beforeEach
該鈎子函數主要用來做權限的管理認證
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // 確保一定要調用 next()
}
})
beforeRouteUpdate
路由參數改變時觸發這個鈎子,例如從/foo/1
和 /foo/2
之間跳轉的時候需要重新請求數據,這種類型的跳轉不會觸發created生命周期函數,可以通過該鈎子函數或者監聽$route來實現
<template>
<div>
{{ count }}
<button @click="goRoute">跳轉路由</button>
</div>
</template>
<script>
export default {
name: "foo",
data() {
return {
count: 0,
};
},
created() {
console.log("id改變了");
this.getData();
},
beforeRouteUpdate(to, from, next) {
this.getData();
next();
},
methods: {
goRoute() {
this.$router.push({
name: "foo",
params: {
id: Math.floor(Math.random() * 10),
},
});
},
getData() {
setTimeout(() => {
this.count = this.$route.params.id * 2;
}, 500);
},
},
};
</script>
beforeRouteLeave
用戶未保存當前的內容就准備跳轉,離開當前路由,可以通過該鈎子彈出一個提示窗口
beforeRouteLeave (to, from, next) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
next()
} else {
next(false)
}
}