Vue 2 路由指南:从基础到高级

注意:对于代码看不清的部分,用鼠标选中就能看到了,背景颜色和字体颜色过于接近,我也不知道怎么调,只能这样子先看着了

一、Vue Router 是什么?

Vue Router 是 Vue.js 官方的路由管理器,它允许你在单页面应用中通过不同的 URL 显示不同的组件。Vue Router 与 Vue.js 核心深度集成,提供了声明式的路由定义、嵌套路由、动态路由、导航守卫等功能,帮助开发者构建复杂的单页面应用。

二、安装与配置

1. 安装 Vue Router

在 Vue 2 项目中,可以通过 npm 或 yarn 安装 Vue Router:注意,vue2要安装3点几的版本

npm install [email protected]
# 或者
yarn add [email protected]

2. 创建路由实例

在项目中创建一个 router.js 文件,用于配置路由:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../components/Home.vue';
import About from '../components/About.vue';

// 使用 Vue Router
Vue.use(VueRouter);

// 定义路由规则
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
];

// 创建路由实例
const router = new VueRouter({
  mode: 'history', // 使用 HTML5 历史模式
  routes
});

export default router;

3. 在主文件中引入路由

main.js 中引入路由实例,并将其挂载到 Vue 实例上:

import Vue from 'vue';
import App from './App.vue';
import router from './router';

new Vue({
  router,
  render: h => h(App)
}).$mount('#app');

三、基本用法

1. 使用  和 

在 Vue 模板中,使用 创建导航链接,使用 显示当前路由对应的组件。

2. 动态路由

动态路由允许你在 URL 中传递参数。例如:

const routes = [
  {
    path: '/user/:id',
    name: 'User',
    component: User
  }
];

在组件中,可以通过 $route.params 获取参数:

3. 嵌套路由

嵌套路由允许你在某个组件内部定义子路由。例如:

const routes = [
  {
    path: '/parent',
    component: Parent,
    children: [
      {
        path: 'child',
        component: Child
      }
    ]
  }
];

在模板中,使用 显示子路由:

四、高级用法

1. 导航守卫

Vue Router 提供了导航守卫(Navigation Guards),可以在路由跳转前后执行一些逻辑。例如:

router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next();
  } else {
    if (!isAuthenticated) {
      next('/login');
    } else {
      next();
    }
  }
});

2. 命名路由

为路由命名后,可以通过名称进行跳转:

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

在模板中使用

关于

3. 编程式导航

除了 ,还可以通过编程方式导航:

this.$router.push({ name: 'About' });

4. 路由懒加载

为了优化应用性能,可以使用路由懒加载:

const routes = [
  {
    path: '/about',
    name: 'About',
    component: () => import('../components/About.vue')
  }
];

你可能感兴趣的:(vue.js,前端,javascript,前端框架)