Search⌘ K
AI Features

The Single Page and Route Middleware

Understand how to enhance a Nuxt 3 project by creating a single page route that handles dynamic image data. Learn to implement route middleware to check for required state and redirect users appropriately when necessary, ensuring smooth navigation and preventing data loss on page refresh.

The modal has a NuxtLink component, which has two tasks. It redirects us to the “/single” URL and also sets the selected image to our state:

Javascript (babel-node)
<!-- components/Modal.vue -->
<NuxtLink to="/single" @click="selectedImage = modalImage"
>More info</NuxtLink
>

Creating the single page

This new route now needs to be handled by adding a new page alongside the existing index.vue:

Pages directory structure
Pages directory structure

Let’s look at the following code:

Javascript (babel-node)
<!-- pages/single.vue -->
<script setup>
const selectedImage = useSelectedImage();
</script>
<template>
<div>
<img
:src="selectedImage.largeImageURL"
:alt="`image by ${selectedImage.user}`"
/>
<p>By: {{ selectedImage.user }}</p>
<p>Tags: {{ selectedImage.tags }}</p>
</div>
</template>
  • Line 4: We store the selected image information from the useState.js file.

  • Line 9–12: We display the large format image.

  • Lines 13–14: We display the image author and the image tags. ...