码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 简陋的nuxt3学习笔记


    目前nuxt3还是beta版本,先浅学一下吧
    bug我感觉还是有点多的,如果遇到任何问题,尝试重新启动一下项目可能有奇效😢

    内容

    • 1. 安装
    • 2. nuxt3目录结构
    • 3. 路由
      • 3.1 nuxt-link标签的使用
      • 3.2 动态路由
        • 3.2.1 单参数传递
        • 3.2.2 多参数传递
      • 3.3 嵌套路由
    • 4. 布局模板
      • 4.1 默认布局
      • 4.2 自定义布局
    • 5. 组件
      • 5.1 组件嵌套目录
      • 5.2 组件懒加载
    • 6. 模块化代码Composable文件夹
      • 6.1 composables的引入规则
    • 7. 数据请求
      • 7.1 useAsyncData的使用
      • 7.2 useFetch的使用
    • 8. middleware路由中间件
      • 8.1 全局路由中间件
      • 8.2 命名路由中间件
    • 9. SEO相关
      • 9.1 useHead()
      • 9.2 使用template中的标签定义head


    1. 安装

    npx nuxi init Project-name
    👇
    cd Project-name
    👇
    npm i


    2. nuxt3目录结构

    • .nuxt 自动生成的目录
    • nuxt.config.ts nuxt项目的配置文件
    • tsconfig.json ts的配置文件

    一些常用的目录,自己建:

    • pages 开发的页面目录
    • components 组件目录
    • assets 静态资源目录
    • layouts 项目布局目录

    如果pages文件夹里没东西,要删除这个文件夹,不然会404


    3. 路由

    第一个页面建立好之后,如何访问这个页面?
    在app.vue中使用标签,这相当于路由的出口
    比如现在pages文件夹中有一个index.vue,想要访问它,无需配置路由

    
    <template>
      <div>
        <nuxt-page>nuxt-page>
      div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    然后在地址栏访问时:http://localhost:3000,就行啦
    ⚠️:因为index是默认的入口,如果你取名叫about.vue,访问时要输入http://localhost:3000/about

    3.1 nuxt-link标签的使用

    nuxt不鼓励用标签进行跳转,而是使用标签
    比如要从index.vue页面跳转到about.vue页面:

    
    <template>
      <div>
        <h1>indexh1>
        <nuxt-link to="/about">to aboutnuxt-link>
      div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3.2 动态路由

    3.2.1 单参数传递

    参数写在页面的文件名里,并且用[]扩起来
    比如新建一个页面叫detail-[id].vue
    这里传递的参数就是id

    --| pages
      --| index.vue
      --| detail-[id].vue
    
    • 1
    • 2
    • 3

    参数接收在模板中可以使用$route.params.id

    <template>
    	<div>id: {{ $route.params.id }}div>
    template>
    
    • 1
    • 2
    • 3

    在index.vue中写一个跳转链接:

    
    <template>
    	<div>
    		<nuxt-link to="/detail-20">to detailnuxt-link>
    	div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    ⚠️:在index.vue中