当前位置:首页 > VUE

vue实现页面跳转路由

2026-02-24 10:16:17VUE

vue-router 基础使用

安装 vue-router 依赖包

npm install vue-router

在 main.js 或 router/index.js 中配置路由

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

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

声明式导航

在模板中使用 <router-link> 组件

<router-link to="/">首页</router-link>
<router-link to="/about">关于</router-link>

添加 active 样式类

<router-link to="/about" active-class="active-link">关于</router-link>

编程式导航

在方法中使用 $router API

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

使用命名路由

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

路由传参

通过 params 传递参数

// 路由配置
{ path: '/user/:userId', component: User }

// 导航方式
this.$router.push('/user/123')

通过 query 传递参数

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

在组件中获取参数

this.$route.params.userId
this.$route.query.id

路由守卫

全局前置守卫

router.beforeEach((to, from, next) => {
  // 登录验证逻辑
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

组件内守卫

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

动态路由

添加动态路由

router.addRoute({
  path: '/new-route',
  component: NewComponent
})

删除路由

router.removeRoute('route-name')

路由懒加载

使用 import() 实现懒加载

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

const router = new VueRouter({
  routes: [{ path: '/user', component: User }]
})

嵌套路由

配置嵌套路由

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

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

vue实现页面跳转路由

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

标签: 跳转路由
分享给朋友:

相关文章

Vue实现路由监

Vue实现路由监

Vue实现路由监听的方法 在Vue中,可以通过多种方式监听路由变化,以下是常见的实现方法: 使用Vue Router的全局前置守卫 router.beforeEach((to, from,…

vue文件实现页面跳转

vue文件实现页面跳转

使用 router-link 实现跳转 在 Vue 模板中直接使用 <router-link> 组件,通过 to 属性指定目标路径: <router-link to="/tar…

vue路由实现iframe

vue路由实现iframe

Vue 路由实现 iframe 的方法 在 Vue 项目中,可以通过路由配置和组件的方式实现 iframe 的嵌入。以下是具体实现步骤: 创建 iframe 组件 新建一个 Vue 组件用于承载 i…

vue路由实现思路

vue路由实现思路

Vue 路由实现思路 Vue 路由的核心是通过 Vue Router 库实现单页应用(SPA)的页面切换,避免整页刷新。以下是关键实现思路: 安装与引入 Vue Router 通过 npm 或 ya…

php实现跳转

php实现跳转

PHP 实现页面跳转的方法 在 PHP 中实现页面跳转有多种方式,以下是常见的几种方法及其适用场景: 使用 header() 函数 通过 header() 函数发送 HTTP 头部信息实现跳转。注意…

php 实现路由

php 实现路由

PHP 实现路由的方法 在 PHP 中实现路由功能可以通过多种方式完成,以下是几种常见的实现方法: 使用原生 PHP 实现简单路由 通过解析 URL 并匹配对应的处理逻辑,可以实现基本的路由功能。以…