Reputation: 563
I have a project using Nuxt 3, with a lot of images in the /public
directory (and subdirectories). Now I would like to implement a simple gallery showing all images in the directory (or specified subdirectory). Is there a way to programmatically access all files in the directory, so that I can just do something like this:
<script setup>
let images = ???
</script>
<template>
<img v-for="image in images" :key="image.path" :scr="image.path" alt="" />
</template>
Upvotes: 0
Views: 2880
Reputation: 949
You could do the following using a composable
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>
Your basically reading all the files in the specified folder which you select by configuring folderPath
then get the relative path of that folder from the root to append it to file paths later (process.cwd()
gets the root project path).
after getting the matched assets and storing the array in files
, we're using map
to construct a new array with correct relative paths of the files in order for nuxt to read it correctly
Upvotes: 1