当前位置:首页 > VUE

vue 怎么实现跳转的

2026-02-22 16:24:28VUE

vue-router 基本跳转方法

安装 vue-router 后,在项目中配置路由表:

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

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

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

声明式导航

在模板中使用 <router-link> 组件实现跳转:

<router-link to="/about">关于我们</router-link>
<router-link :to="{ name: 'About' }">命名路由跳转</router-link>

编程式导航

在组件方法中使用 router 实例进行跳转:

// 字符串路径
this.$router.push('/about')

// 对象形式
this.$router.push({ path: '/about' })

// 命名路由
this.$router.push({ name: 'About' })

// 带查询参数
this.$router.push({ path: '/about', query: { id: 1 } })

// 替换当前路由(不记录历史)
this.$router.replace('/about')

路由传参方式

通过 params 传递参数:

// 路由配置需要定义参数
{
  path: '/user/:id',
  name: 'User',
  component: User
}

// 跳转时传递
this.$router.push({ name: 'User', params: { id: 123 } })

通过 query 传递参数:

this.$router.push({ path: '/user', query: { id: 123 } })

动态路由匹配

路由配置中使用动态字段:

{
  path: '/user/:username/post/:post_id',
  component: UserPost
}

在组件中获取参数:

this.$route.params.username
this.$route.params.post_id

导航守卫控制跳转

全局前置守卫:

router.beforeEach((to, from, next) => {
  // 必须调用 next()
  if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

组件内守卫:

beforeRouteEnter(to, from, next) {
  // 在渲染该组件的对应路由被验证前调用
  next(vm => {
    // 通过 `vm` 访问组件实例
  })
}

路由懒加载

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

const UserDetails = () => import('./views/UserDetails.vue')

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

vue 怎么实现跳转的

标签: 跳转vue
分享给朋友:

相关文章

vue实现过程

vue实现过程

Vue 的实现过程 Vue 的实现过程可以分为多个核心模块,包括响应式系统、虚拟 DOM、模板编译等。以下是 Vue 的主要实现过程分析。 响应式系统 Vue 的响应式系统基于 Object.def…

vue 实现闪烁

vue 实现闪烁

Vue 实现闪烁效果的方法 方法一:使用 CSS 动画 在 Vue 组件中定义一个闪烁的 CSS 动画,通过绑定 class 或 style 来控制元素的闪烁效果。 <template&…

vue实现海报

vue实现海报

Vue 实现海报生成方案 使用 html2canvas 库 html2canvas 是一个将 HTML 元素转换为 Canvas 的库,适合将 Vue 组件渲染为海报图片 安装依赖: npm…

vue实现前端

vue实现前端

Vue 实现前端的核心方法与步骤 安装 Vue 项目 使用 Vue CLI 或 Vite 创建项目。Vue CLI 是传统构建工具,Vite 是新一代轻量级工具。 npm init vue@la…

vue 实现href

vue 实现href

Vue 实现 href 的方法 在 Vue 中实现 href 功能可以通过多种方式,具体取决于需求场景。以下是几种常见的方法: 使用 <a> 标签 直接使用 HTML 的 <a&…

vue代理实现

vue代理实现

Vue 代理实现方法 在 Vue 项目中,配置代理可以解决开发环境下的跨域问题,通常通过修改 vue.config.js 文件实现。以下是几种常见的代理配置方式: 基础代理配置 在 vue.con…