0

I am using a photo gallery component in my project. It requires a path to the folder containing the images. I am unable to find a way to do this. I have created an img directory inside of assets, and I'm using the standard Vue CLI 3 scaffolding. I'm able to use a require('path/to/file/name.png'), but what I need is to be able to bring the whole folder in. I'm unable to figure out a way to do this. I even tried placing the images in a folder inside of public, but no luck.

My structure looks like this:

project/public/img project/src/assets/img/ project/src/components/ 

I need to get the project/src/assets/img path into a component inside of project/src/components/componentName.vue.

I should also mention that I want to be able to access this directory from the script tag, not the template tag.

2 Answers 2

2

You can try something like this:

const requireModule = require.context('../assets/img.',false,/\.png$/) const images = {} requireModule.keys().forEach(filename => { const imageName = fileName.replace(/(\.\/|\.png)/g, ''); images[imageName] = requireModule(fileName) OR images[imageName] = { namespaced: true, ...requireModule(fileName) } }); export default images; 

Then you can import this file

import photos from 'imagesObject.js' for (let key in photos) // do whatever you want with the image 
Sign up to request clarification or add additional context in comments.

Comments

0

Thank you for your answer IVO. That solution did work, but I found another that I wanted to share here for anyone else having a similar problem. The issue I was having was incorrectly referencing the public folder using a relative path instead of BASE_URL. Based on this... The public Folder Vue CLI Documentation

I created a directory inside of /public then referenced it using process.env.BASE_URL. This solved the problem. Here are the relevant snippets:
Javascript:

data () { return { thumbnailDir : process.env.BASE_URL + 'portfolio/' } 

Template:

<transition-group name="thumbnailfade" tag="div"> <img v-for="thumb in filteredImages" :key="thumb.id" @click="showLightbox(thumb.name)" :src="thumbnailDir + thumb.name" :alt="thumb.alt" :title="thumb.alt"/> </transition-group> <lightbox id="mylightbox" ref="lightbox" :images="images" :directory="thumbnailDir" :filter="galleryFilter" :timeoutDuration="5000" /> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.