路由守卫是 Vue.js 中用于拦截和修改页面导航的功能。Vue 中有三种类型的路由守卫:全局守卫、特定路由守卫和组件内守卫。它们可用于验证用户登录、授予或拒绝访问、提示保存更改、执行异步操作等。

Vue 中的路由守卫
什么是路由守卫?
路由守卫是 Vue.js 中的功能,允许开发人员在特定条件下拦截和修改页面导航。
有哪些类型的路由守卫?
立即学习“前端免费学习笔记(深入)”;
Vue 中有三种类型的路由守卫:
如何使用路由守卫?
可以通过以下方式使用路由守卫:
router.js 文件中使用 router.beforeEach() 和 router.afterEach() 方法。beforeEnter 和 afterEach 钩子。beforeRouteEnter、beforeRouteUpdate 和 beforeRouteLeave 钩子。路由守卫有什么用?
路由守卫可用于实现多种用途,包括:
示例:
使用全局守卫强制登录:
<code class="javascript">router.beforeEach((to, from, next) => {
if (to.fullPath !== '/login' && !localStorage.getItem('token')) {
next('/login');
} else {
next();
}
});</code>使用组件内守卫在离开页面之前提示保存更改:
<code class="javascript"><template>
<button @click="leave">Leave</button>
</template>
<script>
export default {
beforeRouteLeave(to, from, next) {
if (this.hasUnsavedChanges) {
const confirmation = confirm('Do you want to leave without saving?');
if (confirmation) {
next();
}
} else {
next();
}
}
};
</script></code>以上就是vue中的路由守卫有哪些的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号