Using Nuxt
About 554 wordsAbout 2 min
NuxtServer-Side RenderingSSR
2025-01-20
Summary of Nuxt 3
- Initialize the project: Create the project and configure nuxt.config.ts using npx nuxi init.
- Pages and routing: Generate routes based on files, supporting dynamic routing and parameterization.
- Data fetching: Use useAsyncData and useFetch to fetch data, supporting server-side rendering.
- Layouts and middleware: Define layouts through the layouts/ directory and control route access permissions with middleware.
- Plugins and modules: Extend functionality through plugins and introduce third-party libraries using modules.
- API routes: Easily define backend interfaces through the server/api directory.
Initialize the Project
npx nuxi init my-nuxt3-app
cd my-nuxt3-app
npm install
Project Directory Structure
├── app.vue # Root component of the application
├── nuxt.config.ts # Configuration file
├── pages/ # Page files, automatically generate routes
├── components/ # Reusable Vue components
├── layouts/ # Page layouts
├── plugins/ # Plugin registration
├── middleware/ # Middleware
├── server/ # API routes and server-side logic
├── composables/ # Composable functions, encapsulate common logic
├── assets/ # Static resources (CSS/JS/Images)
├── public/ # Static files (not processed by Webpack/Vite)
Note
- Composable functions are regular JavaScript functions, usually prefixed with use (e.g., useCounter, useFetch).
- Similar to hooks in the React framework. They only handle logic, not views.
- In Vue 3's composable functions, you can register Vue component lifecycle functions, create reactive states, and use computed, watch, etc.
Key Points
File system-driven routing (pages/ automatically generates routes)
Define dynamic routes through dynamic filenames. In dynamic pages, you can get parameters through useRoute.
pages/posts/[id].vue #->/posts/:id
Data fetching based on asyncData and useFetch
Optional server-side rendering (SSR) and static site generation (SSG)
Configure target: 'server' or 'static' in nuxt.config.js
Vite is the default build tool
useAsyncData
asyncData
is suitable for SSR scenarios, where data is fetched before the page loads and rendered on the server side.
<script setup>
const { data: posts, pending, error } = await useAsyncData('posts', () =>
$fetch('https://jsonplaceholder.typicode.com/posts')
)
</script>
<template>
<div v-if="pending">Loading...</div>
<div v-else-if="error">Error: {{ error.message }}</div>
<ul>
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</template>
useFetch
useFetch
is more suitable for client-side data fetching and also supports SSR, directly returning reactive data by default.
<script setup>
const { data: user } = useFetch('https://jsonplaceholder.typicode.com/users/1')
</script>
<template>
<div>
<h1>User: {{ user.name }}</h1>
</div>
</template>
Define Global Layout in layouts/default.vue
<template>
<div>
<header>Global Header</header>
<NuxtPage />
<footer>Global Footer</footer>
</div>
</template>
Specify Layout in Pages through definePageMeta
<script setup>
definePageMeta({
layout: 'custom' // Use the layout defined in layouts/custom.vue for the current page
})
</script>
Plugins
You can create plugin files in the plugins/ directory.
// plugins/my-plugin.js
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.provide('hello', () => 'Hello from Plugin!')
})
// Use in a component
<script setup>
const hello = inject('hello')
</script>
<template>
<div>{{ hello() }}</div>
</template>
Modules
Nuxt supports module extensions, such as TailwindCSS, Axios, etc.
export default defineNuxtConfig({
modules: ['@nuxtjs/tailwindcss'] // After installation, enable the module in nuxt.config.ts
})
API Routes
You can define API routes in the server/api directory. By introducing ORM frameworks, you can perform complex database operations here.
// server/api/hello.ts
export default defineEventHandler(() => {
return { message: 'Hello from API!' }
})
// Use the API
<script setup>
const { data } = useFetch('/api/hello')
</script>
<template>
<div>{{ data.message }}</div>
</template>
Middleware
Please refer here