Exploring Nuxt 3: How to Dynamically Access /public Directory Assets

For my current project in Nuxt 3, I have numerous images stored in various directories within the /public folder. My goal now is to create a straightforward gallery that showcases all these images from either the main directory or a specific subdirectory. Is there a method for accessing all files in a directory programmatically, allowing me to easily implement the following code snippet:

<script setup>
let images = ???
</script>

<template>
  <img v-for="image in images" :key="image.path" :src="image.path" alt="" />
</template>

Answer №1

If you want to leverage the power of a composable, consider the following approach:

composables/useAssets.js

import fs from 'fs';
import path from 'path';

const folderPath = './public';
const relativeFolderPath = path.relative(process.cwd(), folderPath);

export default function () {
  const files = fs
    .readdirSync(folderPath)
    .filter((file) => file.match(/.*\.(jpg|png?)/gi));

  const filesPaths = files.map(
    (fileName) => `/_nuxt/${relativeFolderPath}/${fileName}`
  );

  return filesPaths;
}

YourComponent.vue

<script setup>
  const assets = useAssets();
</script>

<template>
  <div>
    <img :src="item" v-for="item in assets" :key="item" />
 </div>
</template>

The code above helps you extract all files within a specified folder by configuring folderPath. It then determines the relative path of this folder from the project root for later concatenation with file paths (process.cwd() retrieves the project's root path).

Once the assets matching the criteria are identified and stored in the array files, the map function is used to generate a new array containing correctly formatted relative paths to ensure correct interpretation by nuxt.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigate through the JSON object and generate all possible combinations of nested elements

Here is a JSON object that I need to iterate through in order to generate all possible nested group names: { "groups": [ { "group": "group1", "childrens": [ { "group": "group1_1", ...

Numerous error notifications triggered by a different data field

I attempted to create a dynamic error message: window.Parsley.addValidator('validatorName', { requirementType: 'string', validateString: function (value) { return validateField(value); }, messages: { en: &apo ...

Creating a visually striking layout with Bootstrap card columns masonry effect by seamlessly adjusting card heights to prevent any

When using the bootstrap card columns masonry and a user clicks on a button inside a card, the height of the card changes dynamically by adding a card-footer. However, in certain situations, the cards change position causing a jumpy effect. To see this i ...

Whenever text is present, the sides of my box model, constructed using HTML5 and CSS3, are always pushed downward

When I add extra text to the body of my homepage, it causes a distortion and pushes down the sidebar and advertising boxes on the side. I'm working on this project for class and even though I've asked my teacher for help, she says the code is fin ...

Find and compare certain data points within a single line

My goal is to extract specific values from a URL, focusing on the parameters and their respective values. Since a parameter can appear multiple times in the URL, I need to retrieve all instances along with their corresponding values. &myparameter[123 ...

Discover the latest CSS styles and HTML attributes that impact the dimensions of an image

I am in the process of developing a custom jQuery plugin that will enable me to easily change the "src" attribute of an image on my website based on the width of the browser. However, I've encountered an issue where when the new image is loaded, the ...

Retrieve the value of a keypress in a Vue select field

I am currently utilizing vue-search-select to enable autocomplete on a select field. I am now interested in retrieving the input entered by the user for searching from the select field. I attempted using the keyup event without success. Is there another ...

Why isn't my classList .add method working properly?

I've created a video slider background on my website, but I'm having trouble with the Javacript for video slider navigation. When I click on the button to change the video, nothing happens. The console is showing an error message that says "Canno ...

Is it possible to categorize elements for focus and onblur events?

In my search feature, I have implemented an autocomplete div that appears when the user types in a search field. The issue I am facing is that I want the div to disappear when the user clicks outside of it. Here is what I have attempted: //SHOW THE DIV WH ...

Can values be transferred from an ng-repeat to a JavaScript function?

I am facing an issue with this segment: <tr ng-repeat="data in filtered = (list | filter:search | orderBy : predicate :reverse) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit"> <td>{{data.name}}</td> ...

IE11 encounters an error labeled SCRIPT1010, signaling an expected Identifier when compiled

Lately, I've been encountering a strange issue in Vue.js. Here's the thing: my application runs smoothly on all browsers locally (yes, even IE 11). But when I compile it using npm run build and deploy it to my server (which essentially serves con ...

The CSS method will not function properly on Safari when targeting the specific ID

that.displayIcon = that.scrollPosition / that.headerHeight $('#icon').css({'opacity':that.displayIcon}) that.rotateIcon = Math.min(1,that.scrollPosition/that.headerHeight) $('#icon').css({'transform':'rot ...

What is the process for invoking a JavaScript function from the code-behind of an Asp.Net application?

Here is a sample of my JavaScript function : function NeedToExport() { alert('Time to export your data!'); } Additionally, in my ASP.NET code behind : Page.ClientScript.RegisterStartupScript(this.GetType(), "ExportKey", "NeedToExport();"); ...

Simplifying the structure of deeply nested callbacks

Struggling with learning how to work with callback style programming in Node.js. Specifically, I'm having issues with a query to a MongoDB database. When I pass in a function to execute on the result, it works fine - but I would prefer to simplify and ...

Looking for the Mustache template library?

Can you provide some examples of how mustache can be used effectively? I recently came across it, but I'm struggling to grasp how it differs from the traditional approach of creating template files within frameworks like cakePHP or django, or simply ...

Tips for choosing a single column from a table to copy to the clipboard without including neighboring columns

I'm on the lookout for a jQuery plugin or function that can assist in selecting the text of a specific column for easy copying to the clipboard. Imagine I have a 4x4 table and I drag my cursor from cell R1C2 to R4C2 - I want to be able to select only ...

The axios GET request suddenly transforms into an Options request, returning a 401 Unauthorized status. Miraculously, Post

I am well-versed in the concept of "preflight request" and my server does indeed support options requests. What perplexes me is that I have tested various online API tools like Postman and reqbin, which work perfectly fine. However, when I attempt to use ...

Disable HoverZoom feature for images on the website

Currently building a website that includes various images. I have Imagus (similar to HoverZoom) installed for automatic image enlargement on hover, but I do not want this function for my specific images. I've noticed it works for some images and not ...

"Despite using vue.js mounted function, my data remains unchanged after making asynchronous calls to

After trying to find a solution on the internet for my specific case, I decided to call data from firebase using this line of code: this.$store.dispatch('getConsumptionFromFirebase') However, I encountered an issue where the mounted() functio ...

Can a constructor function be utilized as a parameter type in another function within TypeScript?

Recently, I came across TypeScript and after watching some video reviews, I see great potential in it. It seems to offer better code completion, implicit code documentation, and enhanced type safety for JavaScript. I'm currently in the process of con ...