Is there a way to automatically import all images from a folder in VUE?

I'm attempting to automatically import all images from a folder. Here is what I've tried under // tested:

<template>
  <p>classical art</p>
  <img v-for="image in images" :key="image" :src="image.url" :alt="image.alt" />
</template>

<script>
export default {
  data: function () {
    return {
      name: "classical-art",
      images: [
        { url: require("../assets/images/classical-art/img-00001.jpg"), alt: "první" },
        { url: require("../assets/images/classical-art/img-00002.jpg"), alt: "druhý" },
      ],
    };
  },
};

// tested
const classicalArt = require(`../assets/images/classical-art/.jpg`)

classicalArt.forEach((image) => {
    return image;
});
</script>

<style module lang="scss"></style>

I'm not very familiar with these things, so I'll need some help with this. Maybe I'm just confused, but I can't seem to get it to work. If possible, I would like it to be asynchronous (lazy-loading) or something similar.

----- UPDATE:

I attempted something like this, but still no luck. With require.context, I should be able to accomplish this:

<template>
  <p>classical art</p>
  <img :src="getImgUrl()" v-bind:alt="req" />
</template>

<script>
export default {
  data: function () {
    return {
      name: "classical-art",
    };
  },
  methods: {
    getImgUrl() {
      var req = require.context(
        "../assets/images/classical-art/",
        false,
        /\*.jpg$/
      );
      req.keys().forEach(function (key) {
        req(key);
      });
    },
  },
};
</script>

<style module lang="scss"></style>

I'd like for when I add another image to the classical-art folder, a new <img> tag is created automatically and displays the image without needing to manually update the code.

Could anyone assist me with this?

Answer №1

To properly render images, it is necessary to specify the exact URL for each image by manually entering it in the correct format.

On another note, the concept you have can be achieved using NodeJS. The Node runtime environment allows access to the file system, enabling automatic generation of URL strings for files.

Unfortunately, Vue does not offer direct access to your files, requiring manual importation of every component, file, or image.

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

Utilizing i18n for moment formatting techniques

As I switch from moment to date-fns, I came across this code that involves moment, which I don't quite understand. However, I do comprehend the map function. this.events[0].dates.map(date => moment(date).format(this.$i18n.locale)) I set up an e ...

What is the best practice for importing React components?

In my experience with React, I've noticed two different ways of importing and extending components. The first way that I typically use is shown below. import React from 'react'; class SomeClass extends React.Component { //Some code } ...

How come my form isn't functioning properly on mobile devices?

I recently downloaded a form from the website and integrated it within my desktop site successfully. However, when accessed on mobile devices, specifically iOS, the submit button changes to "sending ..." and the form gets stuck without displaying any erro ...

The ExtJS Grid Filter is being triggered excessively

I am working on an ExtJS 6.2 grid that uses the 'classic' API. Although I am not very experienced with Ext, we have a grid component that we reuse with small modifications in different applications. In one of our apps, we have a text field for fi ...

Prevent the reloading of the page by utilizing Ajax technology when submitting a form in Laravel

I'm facing a challenge with processing a form submit using ajax instead of Laravel to prevent page reloads. Unfortunately, it's not working as expected and I'm struggling to figure out the issue. Despite researching numerous examples online, ...

Searching for li elements that contain text values - a guide

I have a list of letters and I want to filter out any values that contain the text entered by the user in a textbox. Here is the design: Search List: <input type="text" id="txtSearch" /> <ul> <li>Coffee1</li> <li>Coffe ...

What are the reasons behind the pagination with numbers not functioning properly in Vue?

I've encountered an issue with my Vue application using Vuex while implementing pagination. The problem lies in the fact that the events stored are not being displayed, and neither are the page numbers for pagination. Another issue is that the paginat ...

express.static() fails to serve files from public directories when accessed via router paths other than "/"

Express static configuration: app.use(express.static(__dirname + "/public")); Directory Structure: --public --assets --js --[JavaScript scripts] --stylesheets --[CSS files] Defined Routes: const shopRoutes = require('./routes/shopRo ...

Ensure the video fills the entire width of its parent element and adjusts its height accordingly to maintain a 16:9

I am looking to make both videos fill 100% width of their parent element while keeping their aspect ratio intact. The parent element takes up 50% of the window's width, so the videos need to be responsive. I have come across numerous solutions that ...

Is it possible to identify the beginning of a download using Selenium?

Currently, I am using Python and Selenium to download a large batch of files. To ensure that each file is successfully downloaded, I am implementing a basic time.sleep() function, but I want to enhance efficiency and guarantee the completion of each downlo ...

Incorporate text onto an image using Semantic UI

Currently, I am utilizing Semantic UI to display images. While it is functioning well for me in terms of adding text near the image, I desire to have the text positioned on top of the image. Ideally, I would like it to be located on the lower half of the i ...

Encountering an issue with inability to resolve the 'react-navigation-stack' module. Still seeking a solution to this problem

Having trouble with my react navigation in react native. I've already added npm react-navigation-stack and also npm install --save react-native-gesture-handler react-native-reanimated react-native-screens. The error message I'm getting is: Unab ...

Utilize jQuery ajax to pull in data from an external website

I've been doing some research on using jQuery ajax to extract links from an external website, but I'm a bit lost on where to begin. I'm taking on this challenge just to push my skills and see what I can accomplish. While reading about the S ...

Transferring data from local storage to a PHP server using AJAX

My attempt to transfer data from local storage to PHP using AJAX resulted in an error mentioning 'undefined index data'. chart.php <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="t ...

Transform jQuery code to its equivalent in vanilla JavaScript

While I am proficient in using jQuery, my knowledge of pure JavaScript is somewhat limited. Below is the jQuery code that I have been working with: $(document).ready(function() { $.get('http://jsonip.com/', function(r){ var ip_addre ...

I am looking to implement a feature that will disable unchecked checkboxes based on certain conditions in a

Upon selection of an option from a dataset, an API call is triggered. The API response includes an object with a nested array, whose values are listed as checkboxes. Additionally, the API returns a key named choose(const name primaryMax) indicating the max ...

Using PHP and jQuery to generate push notifications can result in issues with server performance

To simulate push notifications using PHP, I have implemented the following method: An AJAX call is made to a server-side script using jQuery. The script includes a for loop with a sleep function after each iteration to introduce delay. If a certain condi ...

Challenges with JavaScript fetching JSON information

Resolved: To enable AJAX functionality, I needed to upload the files to my server. Currently, I am attempting to retrieve stock information from a JSON file, but no data is being displayed. Upon alerting ajax.status, it returned 0 as the result, indicatin ...

Transform uploaded image file into a blob format and store it in a VueJS database

I am facing an issue with my form that has multiple inputs, including one of type "file". My goal is to upload an image and then submit the form to the API for storage in the database. <input name="image" class="w-full border-2 border-gray-200 rounded-3 ...

Implementing universal design in Next.js 14

I'm encountering a problem while trying to use the style jsx global property in the latest version of Next.js. Previously, you would include it in the _app.js file, but since that file no longer exists, I assumed it should be added to the layout.tsx f ...