当前位置:首页 > VUE

vue router 实现

2026-01-07 18:11:06VUE

Vue Router 的实现

Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是 Vue Router 的核心实现方式。

安装 Vue Router

通过 npm 或 yarn 安装 Vue Router:

npm install vue-router

基本配置

在 Vue 项目中引入并配置 Vue Router:

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

Vue.use(VueRouter)

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

const router = new VueRouter({
  routes
})

export default router

路由视图

在根组件中使用 <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>

动态路由

通过冒号 : 定义动态路由参数:

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

在组件中通过 this.$route.params.id 访问参数。

vue router 实现

嵌套路由

通过 children 属性实现嵌套路由:

const routes = [
  {
    path: '/user',
    component: User,
    children: [
      { path: 'profile', component: Profile },
      { path: 'posts', component: Posts }
    ]
  }
]

编程式导航

通过 this.$router.pushthis.$router.replace 实现编程式导航:

this.$router.push('/about')
this.$router.replace('/about')

路由守卫

通过路由守卫控制导航行为:

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

懒加载路由

通过动态导入实现路由懒加载:

vue router 实现

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

命名路由

通过 name 属性为路由命名:

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

使用命名路由导航:

this.$router.push({ name: 'user', params: { id: 123 } })

路由模式

Vue Router 支持 hashhistory 两种模式:

const router = new VueRouter({
  mode: 'history',
  routes
})

滚动行为

通过 scrollBehavior 控制页面滚动行为:

const router = new VueRouter({
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  },
  routes
})

标签: vuerouter
分享给朋友:

相关文章

vue实现aop切面

vue实现aop切面

Vue 实现 AOP 切面编程的方法 在 Vue 中实现 AOP(面向切面编程)可以通过多种方式,以下是几种常见的实现方法: 使用 Vue 混入(Mixins) Vue 的混入机制可以用于实现横切关…

vue实现人脸识别比对

vue实现人脸识别比对

Vue 实现人脸识别比对的方法 使用现成的人脸识别 API 通过调用第三方人脸识别 API(如 Face++、百度 AI、腾讯云等)实现比对功能。注册开发者账号获取 API Key 和 Secret,…

vue实现微博印象

vue实现微博印象

实现微博印象功能的核心思路 微博印象功能通常指用户发布微博后,系统自动分析文本内容并提取关键词或标签,以可视化形式展示。Vue实现该功能需要结合文本分析、关键词提取和前端渲染技术。 文本分析与关键…

vue实现冰墩墩

vue实现冰墩墩

使用 Vue 实现冰墩墩动画 通过 Vue 的动画特性和 SVG 技术,可以动态渲染冰墩墩的形象。以下是具体实现方法: 准备 SVG 素材 冰墩墩的形象通常由多个 SVG 路径组成,包括身体轮廓…

vue实现多选题

vue实现多选题

Vue实现多选题的方法 使用Vue实现多选题功能,可以通过v-model绑定数组、动态渲染选项、以及处理选中状态来实现。以下是一个完整的实现示例: 基础实现代码 <template>…

vue穿梭框组件实现

vue穿梭框组件实现

实现基础穿梭框组件 在Vue中实现穿梭框组件,可以使用<el-transfer>(Element UI)或手动实现。以下是手动实现的核心逻辑: <template> &…