当前位置:首页 > VUE

vue实现导航跳转

2026-01-15 06:54:13VUE

vue-router 基本跳转方法

在 Vue 项目中实现导航跳转主要通过 vue-router 完成。安装路由依赖:

npm install vue-router

在 router/index.js 中配置路由:

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

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

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

声明式导航

使用 <router-link> 组件实现跳转:

<router-link to="/">首页</router-link>
<router-link :to="{ name: 'about' }">关于</router-link>

带参数的跳转示例:

<router-link :to="{ path: '/user', query: { id: 123 } }">用户</router-link>
<router-link :to="{ name: 'profile', params: { username: 'john' } }">个人资料</router-link>

编程式导航

通过 router.push() 方法跳转:

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

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

// 命名路由带参数
this.$router.push({ name: 'user', params: { userId: '123' } })

替换当前路由(不保留历史记录):

vue实现导航跳转

this.$router.replace('/login')

前进/后退导航:

this.$router.go(1)  // 前进
this.$router.go(-1) // 后退

路由守卫控制跳转

全局前置守卫:

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

组件内守卫:

vue实现导航跳转

export default {
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被验证前调用
    next()
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    next()
  }
}

动态路由匹配

带参数的路由配置:

{
  path: '/user/:id',
  component: User,
  props: true // 将参数作为 props 传递
}

在组件中获取参数:

// 通过 props
props: ['id'],

// 或通过 $route
this.$route.params.id

嵌套路由实现

配置子路由:

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

在父组件中添加 <router-view>

<div class="user">
  <h2>User {{ $route.params.id }}</h2>
  <router-view></router-view>
</div>

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

相关文章

vue实现签名

vue实现签名

实现Vue签名功能的步骤 安装签名库 使用vue-signature库可以快速实现签名功能。通过npm或yarn安装: npm install vue-signature --save # 或 y…

vue实现拼音搜索

vue实现拼音搜索

实现拼音搜索的基本思路 拼音搜索的核心是将中文转换为拼音,并在用户输入拼音时匹配对应的中文内容。Vue中可以通过集成拼音转换库(如pinyin或pinyin-pro)实现这一功能。 安装拼音转换库…

vue实现导航切换内容

vue实现导航切换内容

Vue实现导航切换内容的方法 在Vue中实现导航切换内容,可以通过以下方式实现: 使用动态组件 动态组件通过<component :is="currentComponent">实现内容切…

vue实现多用户登录

vue实现多用户登录

实现多用户登录的基本思路 在Vue中实现多用户登录通常需要结合后端API完成身份验证,并通过前端路由、状态管理(如Vuex或Pinia)和本地存储(如localStorage)来管理用户会话。以下是关…

vue实现关键词轮播

vue实现关键词轮播

Vue 实现关键词轮播 基础实现方案 使用 Vue 的 v-for 和 setInterval 实现基础轮播效果: <template> <div class="keyword…

vue实现字母添加排序

vue实现字母添加排序

实现字母添加排序的方法 在Vue中实现字母添加排序功能,可以通过以下步骤完成: 创建Vue实例并定义数据 new Vue({ el: '#app', data: { lette…