Nuxt 3 Cheatsheet
Nuxt 3 Cheatsheet
Nuxt 3 Cheatsheet
CHEAT SHEET
pages
$ npx nuxi init <project-name>
index.vue loads the root path /
$ cd <project-name> posts
$ npm install Installs dependencies […slug].vue […x] catch all route /posts/my-slug
$ npm run dev Runs the project index.vue /posts
users-[group] we can also add params inside a folder . /users-customer
[id].vue [ ] de ines a dynamic route with a param. /users-admin/123
<script setup>
const { data: count, pending, refresh, error } = await useFetch('/api/count')
✅ Instead use const useX = () => useState('x') </script>
<template>
Page visits: {{ count }}
Basic </template>
<script setup>
const counter = useState('counter', () => Math.random() * 1000)
</script>
useAsyncData()
<script setup>
const { data } = await useAsyncData('count', () => $fetch('/api/count'))
Shared state </script>
composables/states.ts
export const useCounter = () => useState<number>('counter', () => 0) 👉 Di erence between useFetch and useAsyncData:
export const useColor = () => useState<string>('color', () => 'pink') useFetch receives a URL and gets that data, whereas useAsyncData might
have more complex logic.
app.vue
useFetch(url) is nearly equivalent to useAsyncData(url, () => $fetch(url))
<script setup>
const color = useColor() // Same as useState('color')
</script>
useLazyFetch() and useLazyAsyncData()
These composables behave identically to useFetch and useAsyncData with
<template>
<p>Current color: {{ color }}</p> the lazy: true option set. In other words, the async function does not block
</template> navigation.
f
f
ff
f
f
f
f
NUXT 3 ESSENTIALS
CHEAT SHEET
Client
Matching route params <script setup>
const config = useRuntimeConfig()
Server routes can use dynamic parameters within brackets in the ile name like console.log('Runtime config:', config)
/api/hello/[name].ts and accessed via event.context.params. if (process.server) {
Catching all routes its as easy as using the spread operator […name] console.log('API secret:',
config.apiSecret)
}
/server/api/hello/[name].ts </script>
Handle ile names can be su ixed with .get, .post, .put, .delete, ... to match request’s. return {
// returns a response object
}
/server/api/test.get.ts })
/server/api/test.post.ts
SERVER MIDDLEWARE
Nuxt will automatically read in any ile in the ~/server/middleware to create server
middleware for your project.
server/middleware/auth.js
f
f
f