In my Vue app, I have set up a route that displays multiple image galleries. When a user clicks on a gallery, they are directed to a dynamic component that shows the images belonging to that specific gallery.
For instance, if the user sees two cards named foo
and bar
, clicking on them will lead them to /gallery/foo
or /gallery/bar
. The structure of my assets folder is as follows:
src/assets/images
├── foo
│ └── 1.jpg
└── bar
└── 2.jpg
Each gallery has its own folder containing all the relevant images. This project is entirely static, with no access to databases or APIs, hence external resources are not applicable here.
I attempted to use Webpack's require.context()
, but encountered issues when trying to use a dynamic path, as documented in Webpack Issue #4772.
The code snippet I experimented with:
data() {
return {
images: null
}
),
mounted() {
this.populatePage();
}
},
methods: {
populatePage() {
const imagePath = `@/assets/images/${this.$route.params.id}/`;
this.images = this.importAll(require.context(imagePath, true, /\.(jpe?g)$/));
},
importAll(r) {
return r.keys().map(r);
}
}
Due to using the variable imagePath
in require.context()
, the above approach did not work as expected. Simply using @/assets/images/
imports all JPG files in the directory, which is not desired.
What would be the most effective way to achieve the intended outcome here? It's crucial to avoid loading irrelevant images, considering the potentially large file sizes (~150kb each at high resolution) even after optimization.
I initially considered importing all images and extracting the folder name via regex from the webpack-generated chunk, but the directory gets omitted and replaced by a hash in the filename. Is there a method to append a directory to filenames in Vue or any other framework?
/img/1.2f159e72.jpg
/img/2.2c1da0da.jpg