当前位置:首页 > VUE

vue router怎么实现

2026-02-18 11:13:46VUE

Vue Router 实现方法

Vue Router 是 Vue.js 的官方路由管理器,用于构建单页应用(SPA)。以下是 Vue Router 的基本实现步骤:

安装 Vue Router

通过 npm 或 yarn 安装 Vue Router:

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

配置路由

在项目中创建路由配置文件(如 src/router/index.js):

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

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

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

export default router

挂载路由

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')

使用 <router-view><router-link>

在组件模板中使用 <router-view> 作为路由出口,并使用 <router-link> 导航:

vue router怎么实现

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

动态路由

可以通过 :param 定义动态路由:

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

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

const userId = this.$route.params.id

编程式导航

使用 router.pushrouter.replace 进行导航:

vue router怎么实现

this.$router.push('/about')
this.$router.push({ name: 'About' })
this.$router.replace('/login')

路由守卫

可以在路由跳转前后进行逻辑控制:

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

嵌套路由

通过 children 配置嵌套路由:

{
  path: '/user',
  component: User,
  children: [
    {
      path: 'profile',
      component: Profile
    },
    {
      path: 'settings',
      component: Settings
    }
  ]
}

在父组件中使用 <router-view> 显示子路由:

<template>
  <div>
    <h2>User</h2>
    <router-view></router-view>
  </div>
</template>

标签: vuerouter
分享给朋友:

相关文章

vue实现iframe

vue实现iframe

Vue 中实现 iframe 的方法 在 Vue 项目中,可以通过多种方式实现 iframe 的嵌入。以下是几种常见的方法: 使用原生 HTML iframe 标签 直接在 Vue 组件的模板中使用…

vue插件实现

vue插件实现

Vue 插件实现方法 Vue 插件是一种向 Vue 应用程序添加全局功能的机制。插件可以包含全局指令、过滤器、混入、实例方法等。 插件的基本结构 一个 Vue 插件通常是一个对象或函数,需要暴露一…

vue 实现工具

vue 实现工具

Vue 实现工具的方法 使用 Vue 实现工具功能可以通过多种方式完成,具体取决于工具的类型和需求。以下是几种常见的方法: 组件化实现 创建一个独立的 Vue 组件来封装工具功能。例如,实现一…

vue实现视频

vue实现视频

Vue 实现视频播放的方法 在 Vue 项目中实现视频播放可以通过多种方式完成,以下是几种常见的方法: 使用 HTML5 的 <video> 标签 在 Vue 组件中直接使用 HTML…

vue 实现滑动

vue 实现滑动

Vue 实现滑动效果的方法 在Vue中实现滑动效果可以通过多种方式,以下是几种常见的方法: 使用CSS过渡和动画 通过Vue的<transition>组件结合CSS过渡或动画实现滑动效果…

vue最佳实现

vue最佳实现

Vue 最佳实践 组件设计 组件应遵循单一职责原则,每个组件只负责一个功能模块。命名采用 PascalCase(如 UserProfile.vue),模板中使用 kebab-case(如 <us…