8、Nuxt3导航路由、路由参数及跳转,组件 Components

8,655 阅读4分钟

在第四章节处理我们的顶部导航我们简单使用到了路由跳转,本章节我们来详细认识一下 路由跳转及参数如何传递

Nuxt3采用的是约定路由,会自动为我们整合路由并且映射pages/目录文件到 routes 配置中。如果我们只有 app.vue,没有创建 pages,那么就不会引入 vue-router。自动生成配置表如下:

下面进入正:

/*                       _oo0oo_
 *                       o8888888o
 *                       88" . "88
 *                       (| -_- |)
 *                       0\  =  /0
 *                     ___/`---'\___
 *                   .' \\|     |// '.
 *                  / \\|||  :  |||// \
 *                 / _||||| -:- |||||- \
 *                |   | \\\  - /// |   |
 *                | \_|  ''\---/''  |_/ |
 *                \  .-\__  '-'  ___/-. /
 *              ___'. .'  /--.--\  `. .'___
 *           ."" '<  `.___\_<|>_/___.' >' "".
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /
 *      =====`-.____`.___ \_____/___.-`___.-'=====
 *                        `=---='
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *          佛祖保佑       永不宕机     永无BUG
 * @Description: 路由及跳转、传参
 * @version:1.2.0
 * @Date: 2022-09-13 16:12:11
 * @Author: wenBin
 */
 
 //自动生成的路由配置表
 [
  {
    path: '/',
    component: '~/pages/index.vue',
    name: 'index',
  }
]

一、Nuxt3入口跳转

1、<Nuxtpage> 在App入口文件添加 <Nuxtpage> 来实现路由跳转,这也是我们页面输出的出口。<NuxtPage>是 Nuxt 自带的内置组件。NuxtPage组件需要显示位于目录中的顶级或嵌套页面/pages

2、<NuxtWelcome> 我们在创建项目的时候,Nuxt3在 App.vue 为我们默认配置的就是 <NuxtWelcome>NUXT使用该<NuxtWelcome>组件在起动模板制成的新项目中向用户致意。它包括指向NUXT文档,源代码和社交媒体帐户的链接。说白了就是一个内置的默认模板 项目运行欢迎页

3、<NuxtLayout>

相信我们大家都已经熟悉 layouts,我们可以使用组件在<NuxtLayout />上激活default布局。包括app.vue error.vue<NuxtLayout />可用于覆盖目录中的default布局app.vueerror.vue甚至是页面组件/pages。该组件接受一个 name,它必须与目录中相应布局文件的名称相匹配/layouts。例如:

<template>
  <NuxtLayout :name="layout">
    <NuxtPage />
  </NuxtLayout>
</template>

<script setup>
    // layouts/custom.vue
    const layout = 'custom'
</script>

4、 <NuxtLoadingIndicator>

Nuxt3 提供<NuxtLoadingIndicator>在页面导航上显示进度条。例如我们可以在 App.vue 使用:

/********
*
*- colo:加载栏的颜色。
*- height**:加载栏的高度,以像素为单位(默认`3`)
*- duration:加载栏的持续时间,以毫秒为单位(默认`2000`)
*- throttle**:限制出现和隐藏,以毫秒为单位(默认`200`)
*
**************/
<template>
  <NuxtLayout>
        <NuxtLoadingIndicator /> <!-- I'm here -->
    <NuxtPage />
  </NuxtLayout>
</template>

5、<NuxtErrorBoundary>

Nuxt3<NuxtErrorBoundary>使用 Vue 的钩子提供组件来处理其默认插槽中发生的客户端错误。例如:

  <template>
  <!-----
  @error="logSomeError",当组件的默认插槽抛出错误时发出的事件
   #error="{ error }",指定在发生错误时显示的后备内容
  --->
  
 <NuxtErrorBoundary @error="logSomeError">
      <!-- ... -->
      <template #error="{ error }">
        <p>An error occurred: {{ error }}</p>
      </template>
    </NuxtErrorBoundary>
  </template>

6、跳转组件<NuxtLink>

Nuxt3 提供<NuxtLink>组件来处理应用程序中的任何类型的链接。

例如我们要跳转到某个地址链接。如下:

<template>
  <!---  NuxtLink 相当于我们的 a 跳转  ---->
  <NuxtLink to="https://nuxtjs.org"> 
    Nuxt website
  </NuxtLink>
  
 <!---  等价于  ---->
  <!-- <a href="https://nuxtjs.org" rel="noopener noreferrer">...</a> -->
</template>

如果我们要实现内部跳转,我们用<NuxtLink>组件链接到项目的另一个页面。如下:

<template>
  <!---- to表示我们要跳转的页面地址  ------>
  <NuxtLink to="/about">
    About page
  </NuxtLink>
  
   <!---  等价于  ---->
  <!-- <a href="/about">...</a> (+Vue Router & prefetching) -->
</template>

我们还可以为 <NuxtLink> 添加### targetrel属性。例如


<template>
  <NuxtLink to="https://twitter.com/nuxt_js" target="_blank">
    Nuxt Twitter
  </NuxtLink>
  <!-- <a href="https://twitter.com/nuxt_js" target="_blank" rel="noopener noreferrer">...</a> -->

  <NuxtLink to="https://discord.nuxtjs.org" target="_blank" rel="noopener">
    Nuxt Discord
  </NuxtLink>
  <!-- <a href="https://discord.nuxtjs.org" target="_blank" rel="noopener">...</a> -->

  <NuxtLink to="https://github.com/nuxt" no-rel>
    Nuxt GitHub
  </NuxtLink>
  <!-- <a href="https://github.com/nuxt">...</a> -->

  <NuxtLink to="/contact" target="_blank">
    Contact page opens in another tab
  </NuxtLink>
  <!-- <a href="/contact" target="_blank" rel="noopener noreferrer">...</a> -->
</template>

二、Nuxt3跳转参数的传递

1、单值、多值传递。例如:

//例如在 index.vue,我要跳转到 video.vue,并把 id 传递过去

<template>
 <h3>动态路由传参</h3>
 
 <!---页面跳转单参数传递---->
 <nuxt-link :to="{name:'video',query:{id:id}}">
     <div class="cont">
        <h3>{{zc.title}}</h3>
        <b></b>
        <span>{{zc.createtime}}</span>
        <i class="arr"></i>
    </div>
 </nuxt-link>
 
  <!---页面跳转多参数传递---->
 <nuxt-link :to="{name:'video',query:{id:id,name:'wo'}}">
     <div class="cont">
        <h3>{{zc.title}}</h3>
        <b></b>
        <span>{{zc.createtime}}</span>
        <i class="arr"></i>
    </div>
 </nuxt-link>
 
 <!---js跳转---->
   <div class="cont" @click = 'goVideo(115)'>
        <h3>js跳转</h3>
        <b></b>
        <span>{{zc.createtime}}</span>
        <i class="arr"></i>
    </div>
</template>

<script setup lang="ts">
    const router = useRouter()
    const goVideo = (id) => {
      router.push({ name: "video",
        query:{
          id:id
          name?:'wo'//参数个数根据自己需要处理
        }
      })
    }
 
</script>

<style scoped>

</style>


//video.vue
<template>
 <h3>我拿到的参数{{ id }}</h3>
 <h3 v-if='name'>我拿到的参数{{ name }}</h3>
</template>

<script setup lang="ts">
    const route = useRoute()
    const id = route.query.id //拿到传递参数 
    const name = route.query.name//拿到传递参数 
 
</script>

<style scoped>

</style>

2、动态路由及路由嵌套,参数获取

我们在创建文件夹或者文件名时包含方括号 [],他将被转换为动态路由。例如:

-| pages/
---| users-[list]/
-----| [id].vue

//我们可以在组件`[id].vue`中获取 `list` 和 `id`,如下:
<NuxtLink to="/users-list/123">管理员123</NuxtLink>

//获取参数展示:
<template>
  {{ $route.params.list }}
  {{ $route.params.id }}
</template>

嵌套路由,目录和文件同名,就是嵌套路由。比如下面:

-| pages/
---| parent/
------| child.vue
---| parent.vue

//child.vue

<template>
  <div>
    <h1>我是子页面</h1>
  </div>
</template

//父组件中使用NuxtChild组件显示嵌套子组件内容,parent.vue:
<template>
  <div>
    <h1>parent page</h1>
    <!-- 子组件输出 -->
    <NuxtChild></NuxtChild>
  </div>
</template>


//我们现在 index.vue 做一个跳转
<NuxtLink to="/parent/child">Parent</NuxtLink>

//此时我们生成的路由如下:
{
  path'/parent',
  children: [
    {
      path'child'
    }
  ]
}


三、组件 Components

之前我们使用 Components 组件是每使用一个就需要我们导入一个,Nuxt3 中组件都是自动导入,我们可以直接在页面使用。例如我们分别定义一个顶部组件底部组件 如下:

/*
 *   佛曰:
 *        写字楼里写字间,写字间里程序员;
 *        程序人员写程序,又拿程序换酒钱。
 *        酒醒只在网上坐,酒醉还来网下眠;
 *        酒醉酒醒日复日,网上网下年复年。
 *        但愿老死电脑间,不愿鞠躬老板前;
 *        奔驰宝马贵者趣,公交自行程序员。
 *        别人笑我忒疯癫,我笑自己命太贱;
 *        不见满街漂亮妹,哪个归得程序员?
 *
 * @Description: 布局组件
 * @version:1.2.0
 * @Date: 2022-09-12 09:25:54
 * @Author: wenBin
 */

components/
--| TheHeader.vue
--| TheFooter.vue


//加入在 我们可以这样使用
<template>
  <div>
    <TheHeader />
    <slot />
    <TheFooter />
  </div>
</template>

//注意:如果我们的组件有嵌套关系,如下:
components/
--| common/
----| single/
------| Button.vue

//那么我们在使用时,**组件名称将会基于路径和文件名连起来** 如 `CommonSingleButton`,即
<CommonSingleButton />

<script setup lang="ts">
 
</script>

<style scoped>

</style>

组件的 懒加载,在组件名前面加上Lazy前缀,则可以按需懒加载该组件。例如:

<template>
  <div>
    <h1>懒加载</h1>
    <LazyTheHeader v-if="show" />
  </div>
</template>

<script setup>
  import {ref} from 'vue'
  const show = ref(false)
</script>

总结,在开发过程中,Nuxt3导航路由、路由参数及跳转,组件 Components是使用频率最高的,因此我们要准确掌握,以便我们后续加速开发得心应手。