详解Vue3中的嵌套路由和编程式路由

在这里插入图片描述

本文主要介绍Vue3中的基础路由和动态路由。

Vue3中的路由使用的是Vue Router库,它是一个官方提供的用于实现应用程序导航的工具。Vue Router在Vue.js的核心库上提供了路由的功能,使得我们可以在单页应用中实现页面的切换、跳转和参数传递等功能。

一、嵌套路由

在Vue.js 3中,嵌套路由允许我们在一个页面中创建多个层次的子路由。这可以帮助我们组织和管理复杂的应用程序结构。

要使用嵌套路由,我们需要使用Vue Router来设置路由。具体步骤如下:

  1. 首先,安装Vue Router。可以使用npm或yarn等包管理器进行安装:
npm install vue-router@next
  1. 在main.js(或其他适当的文件)中导入Vue Router,并创建一个新的路由实例:
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    // 在这里定义顶级路由和嵌套路由
  ]
})

createApp(App).use(router).mount('#app')
  1. 在路由配置中,我们可以定义顶级路由和嵌套路由。嵌套路由使用children属性,其中可以定义子路由。
const routes = [
  {
    path: '/',
    component: Home
  },
  {
    path: '/about',
    component: About,
    children: [
      {
        path: '',
        component: AboutHome
      },
      {
        path: 'info',
        component: AboutInfo
      },
      {
        path: 'contact',
        component: AboutContact
      }
    ]
  }
]

在上面的示例中,我们定义了两个路由:根路由’/‘和嵌套路由’/about’。嵌套路由有3个子路由:‘/’、‘/info’和’/contact’。

  1. 在App.vue中,我们可以使用组件来显示当前路由的内容:
<template>
  <div>
    <router-view></router-view>
  </div>
</template>
  1. 在子组件中,我们可以通过路由对象$router来导航到嵌套路由:
<template>
  <button @click="$router.push('/about/info')">Go to About Info</button>
</template>

以上就是Vue 3中使用嵌套路由的基本步骤。通过嵌套路由,我们可以构建复杂的页面布局和导航结构。

下面是一个完整的示例,展示了如何在Vue 3中使用嵌套路由:

// main.js

import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import Home from './components/Home.vue'
import About from './components/About.vue'
import AboutHome from './components/AboutHome.vue'
import AboutInfo from './components/AboutInfo.vue'
import AboutContact from './components/AboutContact.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      component: Home
    },
    {
      path: '/about',
      component: About,
      children: [
        {
          path: '',
          component: AboutHome
        },
        {
          path: 'info',
          component: AboutInfo
        },
        {
          path: 'contact',
          component: AboutContact
        }
      ]
    }
  ]
})

createApp(App).use(router).mount('#app')
<!-- App.vue -->
<template>
  <div>
    <h1>Vue Router Nesting Example</h1>
    <router-view></router-view>
  </div>
</template>
<!-- Home.vue -->
<template>
  <div>
    <h2>Home</h2>
    <p>Welcome to the homepage</p>
  </div>
</template>
<!-- About.vue -->
<template>
  <div>
    <h2>About</h2>
    <router-link to="/about">Home</router-link>
    <router-link to="/about/info">Info</router-link>
    <router-link to="/about/contact">Contact</router-link>
    <router-view></router-view>
  </div>
</template>
<!-- AboutHome.vue -->
<template>
  <div>
    <p>Information about the company</p>
  </div>
</template>
<!-- AboutInfo.vue -->
<template>
  <div>
    <p>Contact information</p>
  </div>
</template>
<!-- AboutContact.vue -->
<template>
  <div>
    <p>Contact details</p>
  </div>
</template>

在上述示例中,我们创建了一个简单的嵌套路由结构,其中包含主页、关于页面和关于页面的子页面。点击About页面上的链接,可以动态加载相应的子页面。

二、编程式路由

编程式路由是指通过编码来进行路由的跳转和导航,而不是通过用户的交互操作来实现。在Vue 3中,使用编程式路由可以使用router实例的方法来实现。

首先,我们需要在Vue应用程序的根实例中创建一个路由器实例。可以使用createRouter函数来创建一个新的路由器实例,并将其挂载到Vue应用程序上。

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

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

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

const app = createApp(App)
app.use(router)
app.mount('#app')

在上述例子中,我们创建了一个简单的路由器实例,该实例具有一个基本路由,该路由将根路径/映射到名为Home的组件。

然后,我们可以在Vue组件中使用router实例的方法来进行编程式导航。

export default {
  methods: {
    goToHome() {
      this.$router.push('/')
    }
  }
}

在上述示例中,我们定义了一个名为goToHome的方法,当调用该方法时,将路由导航到根路径/

除了push方法外,router实例还提供了其他导航方法,例如replacegobackforward,可以根据具体需要选择适合的方法。

// 替换当前路由
this.$router.replace('/other-path')

// 在浏览器历史记录中后退一步
this.$router.back()

// 在浏览器历史记录中前进一步
this.$router.forward()

// 向前或向后导航几个步骤
this.$router.go(1)  // 前进一步
this.$router.go(-1)  // 后退一步

通过使用这些方法,我们可以在Vue 3中实现编程式路由。这对于需要在组件之间进行动态导航的情况非常有用。

在使用编程式路由时,有几个需要注意的地方:

  1. 获取router实例: 在Vue 3中,可以通过this.$router来获取路由器实例。但是需要注意的是,在使用this.$router之前,需要确保已经通过app.use(router)将路由器实例挂载到Vue应用程序上。

  2. 组件中的this指向问题: 在Vue 3中,组件的选项中没有this属性,因此无法直接使用this来访问$router实例。为了解决这个问题,可以使用injectprovide提供和注入router实例。

    // 在main.js中提供router实例
    app.provide('router', router)
    
    // 在组件中注入router实例
    export default {
      inject: ['router'],
      methods: {
        goToHome() {
          this.router.push('/')
        }
      }
    }
    

    通过在根组件中提供router实例,并在组件中注入,可以解决在组件中使用编程式路由时的this指向问题。

  3. 引入路由相关的函数: 在Vue 3中,需要使用createRoutercreateWebHistory这两个函数来创建路由器实例和路由历史实例。需要确保正确引入这些函数。

    import { createRouter, createWebHistory } from 'vue-router'
    
  4. 路由跳转的路径格式: 在编程式路由中,需要注意路由路径的格式。路径应该是字符串,并以斜杠/开头。

    this.$router.push('/home')  // 正确
    this.$router.push('home')   // 错误,缺少斜杠
    
  5. 路由导航的生命周期钩子: 在Vue 3中,路由导航的生命周期钩子函数有所变化。可以使用beforeRouteEnterbeforeRouteUpdatebeforeRouteLeave等生命周期钩子函数来处理路由的导航。需要注意根据Vue 3的生命周期钩子函数文档来使用正确的钩子函数。

这些就是在使用编程式路由时需要注意的主要方面。确保在使用编程式路由时遵循这些注意事项,可以避免常见的问题和错误。

  • 25
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专业研究祖传Bug编写术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值