夜猫子的知识栈 夜猫子的知识栈
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

夜猫子

前端练习生
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《Web Api》
    • 《ES6教程》
    • 《Vue》
    • 《React》
    • 《TypeScript》
    • 《Git》
    • 《Uniapp》
    • 小程序笔记
    • 《Electron》
    • JS设计模式总结
  • 《前端架构》

    • 《微前端》
    • 《权限控制》
    • monorepo
  • 全栈项目

    • 任务管理日历
    • 无代码平台
    • 图书管理系统
  • HTML
  • CSS
  • Nodejs
  • Midway
  • Nest
  • MySql
  • 其他
  • 技术文档
  • GitHub技巧
  • 博客搭建
  • Ajax
  • Vite
  • Vitest
  • Nuxt
  • UI库文章
  • Docker
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 技术文档

  • GitHub技巧

  • 博客搭建

  • Ajax

  • Vite

  • Vitest

  • Nuxt

    • SSR
    • Nuxt基础
      • 安装
        • 创建项目
        • 安装依赖
        • 启动
      • 获取数据
        • 在服务端获取数据
        • useFetch
        • useLazyFetch
        • 只选取你需要使用的数据
      • State
        • 签名
        • 基本用法
        • 共享状态
      • 运行配置
        • 公开运行时配置
        • 访问运行时配置
        • API 路由 API routes
        • 输入运行时配置 Typing runtime config
      • NuxtApp
        • 获取 NuxtApp 实例
        • 提供助手
      • Cookies
        • 配置项[#](https://www.nuxtjs.org.cn/usage/cookies.html#配置项)
        • API 路由中处理 cookies
  • UI库文章

  • Docker

  • 技术
  • Nuxt
夜猫子
2022-09-22
目录

Nuxt基础

# 安装

# 创建项目

打开 Visual Studio Code , 打开内置终端并输入下面命令创建一个 nuxt 项目:

npx nuxi init nuxt3-app
1

# 安装依赖

yarn
1

# 启动

使用 yarn dev 以 开发模式启动 nuxt:

yarn dev
1

# 获取数据

# 在服务端获取数据

因为Nuxt3是SSR的方案,所以你可能不仅仅只是想要在浏览器端发送请求获取数据,还想在服务器端就获取到数据并渲染组件。

Nuxt3提供了 4 种方式使得你可以在服务器端异步获取数据

  • useAsyncData
  • useLazyAsyncData (useAsyncData+lazy:true)
  • useFetch
  • useLazyFetch (useFetch+lazy:true)

注意:他们只能在**setup**或者是生命周期钩子中使用

# useFetch

在pages目录、components目录和plugins目录下使用useFetch也同样可以获取到任意的 URL 资源。该方法实际上是对 useAsyncData 和$fetch 的封装,提供了一个更便捷的封装方法。(它会根据 URL 和 fetch 参数自动生成一个 key,同时推断出 API 的响应类型)

//useFetch用法
const {
  data: Ref<DataT>,// 返回的数据结果
  pending: Ref<boolean>,// 是否在请求状态中
  refresh: (force?: boolean) => Promise<void>,// 强制刷新数据
  error?: any// 请求失败返回的错误信息
} = useFetch(
    url: string,
    options?: { lazy: boolean, server: boolean }
  // options.lazy,是否在加载路由后才请求该异步方法,默认为false
  // options.server,是否在服务端请求数据,默认为true
  // options.default,异步请求前设置数据data默认值的工厂函数(对lazy:true选项特别有用)
  // options.transform,更改fn返回结果的函数
  // options.pick,只从数组中指定的key进行缓存
)

//可以看到useFetch和useAsyncData的返回对象是一样的,useFetch传参更便捷,不需要在fn中手动使用$fetch
useAsyncData(key: string,fn: () => Object,options?: { lazy: boolean, server: boolean })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script setup>
const { data } = await useFetch('/api/count')
</script>

<template>
  Page visits: {{ data.count }}
</template>
1
2
3
4
5
6
7

# useLazyFetch

这个封装方法等同于是,使用useFetch方法默认配置了lazy:true,执行异步函数时不会阻塞路由的执行。也意味着你必须处理数据为null的情况(比如说,在default返回的工厂函数中设置一个默认值)。

# 只选取你需要使用的数据

通过异步请求回来的数据都会存储在页面 payload 中。意味着,可能会存在没有用在你的组件的数据也加载到了 payload 中。我们强烈推荐你只选取必须使用在组件上的数据

// /api/mountains/everest
{

  "title": "Mount Everest",
  "description": "Mount Everest is Earth's highest mountain above sea level, located in the Mahalangur Himal sub-range of the Himalayas. The China–Nepal border runs across its summit point",
  "height": "8,848 m",
  "countries": [
    "China",
    "Nepal"
  ],
  "continent": "Asia",
  "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Everest_kalapatthar.jpg/600px-Everest_kalapatthar.jpg"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
// 组件中只使用到了title和description,useFetch使用option的pick参数来指定key
<script setup>
const { data: mountain } = await useFetch('/api/mountains/everest', {
  pick: ['title', 'description'],
})
</script>

<template>
  <h1>{{ mountain.title }}</h1>
  <p>{{ mountain.description }}</p>
</template>
1
2
3
4
5
6
7
8
9
10
11

# State

Nuxt 提供可组合的 useState 来创建跨组件的并且对 SSR 友好的响应式状态。

useState 是一个 SSR 友好的 ref 替代品。它的值将会在服务端渲染(客户端渲染期间)后保留,并且使用唯一的键在所有组件之间共享。

# 签名

useState<T>(key: string, init?: () => T): Ref<T>
1
  • key :唯一的键确保数据请求能够正确并且不被重复
  • init :在 state 还未初始化时提供初始值的函数
  • T :(仅用作于 typescript )描述 state 的类型

useState 仅在 setup 和 生命周期钩子 中生效。

# 基本用法

在这个例子中,我们使用一个组件内部的 counter 状态,任何其他使用 useState('counter') 的组件都将共享同一个响应式状态。

<script setup>
const counter = useState('counter', () => Math.round(Math.random() * 1000))
</script>

<template>
  <div>
    Counter: {{ counter }}
    <button @click="counter++">+</button>
    <button @click="counter--">-</button>
  </div>
</template>
1
2
3
4
5
6
7
8
9
10
11

# 共享状态

Nuxt 具有自动导入功能(composable),可以定义全局的安全类型状态并且在整个应用中导入。

// composables/states.ts
export const useCounter = () => useState<number>('counter', () => 0)
export const useColor = () => useState<string>('color', () => 'pink')
1
2
3
<script setup>
const color = useColor() // Same as useState('color')
</script>

<template>
  <p>Current color: {{ color }}</p>
</template>
1
2
3
4
5
6
7

# 运行配置

# 公开运行时配置

在nuxt.config 文件中定义运行时配置,可以使用 privateRuntimeConfig 或 publicRuntimeConfig 选项 (opens new window)(根据是否希望在应用程序的客户端部分可以访问它来选择使用)。

提供配置的最常用方法是使用 环境变量 (opens new window) 。 Nuxt CLI 内置 dotenv (opens new window) 支持。

除了一些进程(process)环境变量之外,如果在项目的根目录中有一个 .env 文件,它将自动加载到 process.env 中,并且可以在 nuxt.config 文件和模块中访问。

示例:

BASE_URL=https://nuxtjs.org
API_SECRET=api_secret_token
1
2
export default defineNuxtConfig({
  publicRuntimeConfig: {
    BASE_URL: process.env.BASE_URL,
  },
  privateRuntimeConfig: {
    API_SECRET: process.env.API_SECRET,// 仅服务端可用,会覆盖publicRuntimeConfig的配置
  },
})
1
2
3
4
5
6
7
8

# 访问运行时配置

在 Nuxt 应用程序的 Vue 实例中,需要调用 useRuntimeConfig() 来访问运行时配置。

注意:客户端和服务器端的行为是不同的

  • 在客户端,只有 publicRuntimeConfig 可用,并且该对象是可修改的响应式对象。
  • 在服务器端,publicRuntimeConfig 和 privateRuntimeConfig 被合并并且对象是只读的以避免上下文共享。
<template>
  <div>
    <div>Token: {{ config.API_AUTH_TOKEN }}</div>
  </div>
</template>

<script setup>
const config = useRuntimeConfig()
</script>
1
2
3
4
5
6
7
8
9

# API 路由 API routes

在 API 路由中,您可以通过直接从虚拟 #config 导入来访问运行时配置。

import config from '#config'

export default async () => {
  const result = await $fetch('https://my.api.com/test', {
    headers: {
      Authorization: `Bearer ${config.API_AUTH_TOKEN}`,
    },
  })
  return result
}
1
2
3
4
5
6
7
8
9
10

# 输入运行时配置 Typing runtime config

目前可以手动输入运行时配置文件。

declare module '@nuxt/schema' {
  interface PublicRuntimeConfig {
    testConfig: string
  }
  interface PrivateRuntimeConfig {
    token: string
  }
}
// 确保在扩充类型时 import/export 某些比较重要的内容
export {}
1
2
3
4
5
6
7
8
9
10

# NuxtApp

# 获取 NuxtApp 实例

在组合函数、组件以及插件中通过 useNuxtApp 访问 nuxtApp 实例。

import { useNuxtApp } from '#app'

function useMyComposable() {
  const nuxtApp = useNuxtApp()
  // 获取运行时nuxtApp实例
}
1
2
3
4
5
6

为了便利,插件也可以接收 nuxtApp 作为第一个参数。

# 提供助手

您可以为所有组合函数以及所有应用提供助手,这通常出现在一个 Nuxt 插件里。

const nuxtApp = useNuxtApp()
nuxtApp.provide('hello', (name) => `Hello ${name}!`)

console.log(nuxtApp.$hello('name')) // 打印 "Hello name!"
1
2
3
4

在 Nuxt2 插件里,这被定义为注入方法。

# Cookies

Nuxt 为读取和写入 cookies 提供了一套针对服务端渲染友好的组合式 api。

const cookie = useCookie(name, options) // useCookie 将自动转义结果成 JSON 格式。
1

# 配置项# (opens new window)

组合式 Cookie 接受几个配置项来让你修改 cookie 的行为。

大部分配置项是直接引用的 cookie (opens new window)包中的内容。

# API 路由中处理 cookies

你可以使用h3 (opens new window)包中的useCookie和setCookie在访问服务器的 API 路由时候处理 cookie 的值。

示例:

import { useCookie, setCookie } from 'h3'

export default (req, res) => {
  // Read counter cookie
  let counter = useCookie(req, 'counter') || 0

  // Increase counter cookie by 1
  setCookie(res, 'counter', ++counter)

  // Send JSON response
  return { counter }
}
1
2
3
4
5
6
7
8
9
10
11
12
编辑 (opens new window)
上次更新: 2023/7/11 18:57:41
SSR
iconify

← SSR iconify→

最近更新
01
IoC 解决了什么痛点问题?
03-10
02
如何调试 Nest 项目
03-10
03
Provider注入对象
03-10
更多文章>
Copyright © 2019-2025 Study | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式