当前位置:首页 > VUE

vue 实现跳转

2026-03-27 20:49:23VUE

路由跳转(Vue Router)

在 Vue 项目中,通常使用 Vue Router 实现页面跳转。确保已安装并配置 Vue Router。

安装 Vue Router

npm install 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: '/', component: Home },
  { path: '/about', component: About }
]

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

export default router

声明式导航 在模板中使用 <router-link> 实现跳转:

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

编程式导航 在组件方法中使用 router.push 实现跳转:

methods: {
  goToAbout() {
    this.$router.push('/about')
  }
}

动态路由跳转

通过参数传递实现动态路由跳转。

配置动态路由

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

跳转到动态路由

this.$router.push('/user/123')

获取路由参数 在目标组件中获取参数:

this.$route.params.id

命名路由跳转

通过路由名称实现跳转,便于维护。

配置命名路由

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

跳转到命名路由

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

路由传参

除了动态路由参数,还可以通过查询参数传递数据。

传递查询参数

this.$router.push({ path: '/about', query: { name: 'test' } })

获取查询参数

this.$route.query.name

路由重定向

在路由配置中设置重定向。

配置重定向

const routes = [
  { path: '/home', redirect: '/' }
]

路由守卫

通过路由守卫控制跳转逻辑。

全局前置守卫

router.beforeEach((to, from, next) => {
  // 跳转前逻辑
  next()
})

组件内守卫

beforeRouteEnter(to, from, next) {
  // 组件进入前逻辑
  next()
}

外部链接跳转

跳转到非 Vue 路由的外部链接。

使用 window.location

window.location.href = 'https://example.com'

使用 <a> 标签

<a href="https://example.com" target="_blank">External Link</a>

跳转回退

返回上一页或指定页数。

返回上一页

this.$router.go(-1)

返回首页

vue 实现跳转

this.$router.push('/')

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

相关文章

vue实现发送值接受值

vue实现发送值接受值

Vue 实现父子组件传值 父组件向子组件传值(props) 父组件通过 v-bind 或简写 : 向子组件传递数据。子组件通过 props 接收数据。 父组件代码: <template&g…

vue实现遮罩

vue实现遮罩

Vue 实现遮罩层的方法 在 Vue 中实现遮罩层可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-show 或 v-if 控制显示 通过 Vue 的指令动态控制遮罩层的显示与隐藏。…

vue实现handsontable

vue实现handsontable

Vue 中实现 Handsontable 要在 Vue 项目中集成 Handsontable,可以使用官方提供的 @handsontable/vue 封装库。以下是一个完整的实现步骤。 安装依赖 确…

vue 实现工具

vue 实现工具

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

vue 实现后退

vue 实现后退

实现后退功能的方法 在Vue中实现后退功能通常需要结合浏览器历史记录API或Vue Router的导航方法。以下是几种常见的实现方式: 使用Vue Router的go方法 this.$router…

vue实现curd

vue实现curd

Vue实现CRUD操作 初始化Vue项目 使用Vue CLI创建新项目,安装必要依赖如axios用于HTTP请求 vue create crud-demo cd crud-demo npm inst…