Vue Router 核心点


1. 路由配置(Routes)

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
];

2. 路由模式(History vs Hash)

// history 模式(URL 不带 #)
const router = createRouter({
  history: createWebHistory(),
  routes
});

// hash 模式(URL 带 #)
const router = createRouter({
  history: createWebHashHistory(),
  routes
});

3. 路由导航(编程式)

// 跳转到 /home
router.push('/home');

// 替换当前路由
router.replace('/login');

4. 路由参数和查询参数

// 动态参数配置
{ path: '/user/:id', component: User }

// 访问时获取参数
this.$route.params.id

// 查询参数
this.$route.query.page

5. 嵌套路由和命名视图

const routes = [
  {
    path: '/user',
    component: User,
    children: [
      { path: 'profile', component: UserProfile },
      { path: 'posts', component: UserPosts }
    ]
  }
];

// 命名视图示例
const routes = [
  {
    path: '/layout',
    components: {
      default: DefaultView,
      sidebar: SidebarView,
      footer: FooterView
    }
  }
];

6. 路由守卫(导航守卫)

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isLoggedIn()) {
    next('/login');
  } else {
    next();
  }
});

7. 路由懒加载

const About = () => import('./components/About.vue');

const routes = [
  { path: '/about', component: About }
];

8. 路由元信息(meta)

const routes = [
  {
    path: '/admin',
    component: Admin,
    meta: { requiresAuth: true }
  }
];

// 使用
if (to.meta.requiresAuth) { /* 校验权限 */ }

9. 滚动行为控制

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    return savedPosition || { top: 0 };
  }
});

10. 路由重定向和别名

const routes = [
  { path: '/home', component: Home },
  { path: '/', redirect: '/home' }, // 重定向
  { path: '/u/:id', component: User, alias: '/user/:id' } // 别名
];

Vue2 和 Vue3 的区别

讲解 Vue Router 的路由守卫及应用场景

评 论
请登录后再评论