2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
In Vue, route interceptors are mainly used to intercept and process before navigating to a route or leaving a route. This mechanism allows developers to execute specific logic before or after route navigation occurs, such as permission verification, data loading, page jump, etc.
In Vue Router, route interceptors can be implemented in the following ways:
Global Before Guards:
router.beforeEach(to, from, next)
: Register a global pre-guard. When route navigation is triggered, the guard will be called before the route changes.- router.beforeEach((to, from, next) => {
- // 检查用户权限
- if (!userAuthenticated) {
- next('/login'); // 未认证跳转到登录页
- } else {
- next(); // 已认证则放行
- }
- });
2. Global Resolve Guards:
router.beforeResolve(to, from, next)
: Registers a global resolution guard, which is called after the global pre-guard and before the navigation is confirmed. - router.beforeResolve((to, from, next) => {
- // 在导航被确认之前,进行数据加载等操作
- fetchData().then(() => {
- next();
- });
- });
3. Per-Route Guard:
beforeEnter
field to add guard logic to a single route.- const route = {
- path: '/profile',
- component: Profile,
- beforeEnter: (to, from, next) => {
- // 检查用户是否有权限访问该路由
- if (userHasAccess) {
- next();
- } else {
- next('/403'); // 没有权限跳转到403页面
- }
- }
- };
4. In-Component Guards:
beforeRouteEnter
, beforeRouteUpdate
, andbeforeRouteLeave
Hook functions, which are called when the router navigates to the current component, when the current component is reused, and when the current component is left.- export default {
- beforeRouteEnter (to, from, next) {
- // 在路由导航进入该组件前执行逻辑
- next(vm => {
- // 可以访问实例 `vm`
- });
- },
- beforeRouteUpdate (to, from, next) {
- // 在当前路由改变,但是该组件被复用时调用
- // 可以访问组件实例 `this`
- // 通常用于更新组件的数据
- next();
- },
- beforeRouteLeave (to, from, next) {
- // 在导航离开该组件的对应路由时调用
- // 可以访问组件实例 `this`
- next();
- }
- }
These routing interceptor mechanisms can help developers control the navigation process of applications at different levels and scenarios, implement functions such as permission control, data preloading, page jump, etc., so as to better manage and optimize the interactive experience of front-end applications.