当前位置:首页 > VUE

vue路由实现步骤

2026-02-20 03:25:40VUE

Vue 路由实现步骤

安装 Vue Router
通过 npm 或 yarn 安装 Vue Router 依赖包:

npm install vue-router
# 或
yarn add vue-router

创建路由配置文件
在项目中新建一个路由配置文件(如 src/router/index.js),引入 Vue 和 Vue Router,并定义路由规则:

import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';

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

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;

挂载路由到 Vue 实例
main.js 中导入路由配置并挂载到 Vue 应用:

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

const app = createApp(App);
app.use(router);
app.mount('#app');

添加路由视图容器
在根组件(如 App.vue)中添加 <router-view> 标签作为路由内容的渲染出口:

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

导航链接的使用
在组件中使用 <router-link> 实现路由跳转,例如:

<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>

动态路由与参数传递
定义动态路由时,使用冒号 : 标记参数,例如:

{ path: '/user/:id', component: User }

在目标组件中通过 useRoute 获取参数:

import { useRoute } from 'vue-router';
const route = useRoute();
console.log(route.params.id);

嵌套路由配置
通过 children 属性实现嵌套路由,例如:

{
  path: '/parent',
  component: Parent,
  children: [
    { path: 'child', component: Child }
  ]
}

在父组件模板中添加 <router-view> 作为子路由出口。

路由守卫
使用全局或局部路由守卫控制导航逻辑,例如:

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

懒加载路由组件
通过动态导入优化性能,例如:

{ path: '/profile', component: () => import('../views/Profile.vue') }

vue路由实现步骤

标签: 路由步骤
分享给朋友:

相关文章

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 中实现路由通常使用 Vue Router 库。以下是具体的实现步骤: 安装 Vue Router 在项目中通过 npm 或 yarn 安装 Vue Router:…

php 路由实现

php 路由实现

PHP 路由实现方法 在 PHP 中实现路由功能有多种方式,以下是几种常见的实现方法: 使用原生 PHP 实现 通过解析 URL 并匹配对应的控制器和动作: $request = $_SERV…

react如何使用路由

react如何使用路由

使用 React Router 的基本方法 React Router 是 React 应用中实现路由功能的核心库。以下是基本使用方法: 安装 React Router 依赖包: npm ins…

vue实现路由跳转

vue实现路由跳转

路由跳转的基本方法 在Vue中,路由跳转可以通过vue-router实现。vue-router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。以下是几种常见的路由跳转方式。 声明式导…

vue路由实现登录

vue路由实现登录

路由守卫实现登录验证 在Vue项目中,可以通过路由守卫(Navigation Guards)来实现登录验证逻辑。路由守卫能在路由跳转前、跳转后或跳转时进行拦截处理。 安装路由依赖 npm in…

vue路由实现模式

vue路由实现模式

Vue路由实现模式 Vue Router 提供了两种路由实现模式:Hash 模式和 History 模式。两种模式的主要区别在于 URL 的表现形式以及后端支持的需求。 Hash 模式 Hash…