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

Is it possible to load babel-polyfill using <script async> tag?

I have created a modal dialog on my webpage that appears when certain interactions occur. Utilizing React, I used webpack to generate a compact bundle that can be added to my page using a script tag. Since it incorporates Generators and needs to support ...

Troubleshooting: Why is the Vue search feature in v-data-table not functioning properly

My issue involves using computed values to populate my v-data-table, and I am struggling to resolve the search functionality. Additionally, I would like to re-enable column sorting if possible. Below is the code for my v-Data-Table: <v-data-table ...

Pass an array from a script file in JavaScript to index.js within the Express framework

I've encountered a challenge in sending an array (or JSON object) from script.js to index.js, my express server file. I've explored various solutions such as passing the variable through an HTML file and then to another JavaScript file, utilizing ...

Is the × symbol added from JavaScript not able to be clicked on?

In my javascript code, I have added HTML content dynamically using the following method: var response = { message: "sample messsage" }; $('#main-content').append( '<div class="alert alert-danger alert-dismissable">'+ & ...

Sending a form without the need to reload the page

While it's known that Ajax is the preferred method to submit a form without refreshing the page, going through each field and constructing the Post string can be time-consuming. Is there an alternative approach that utilizes the browser's built-i ...

The state of my React components keeps disappearing

Within my code, I have implemented a click event on the InterestBox to trigger updates in its appearance and alter the state of its parent container. However, despite inspecting the element using React Developer Tools and attempting API requests, the stat ...

Is there a way to dynamically toggle the visibility of a floating textarea between on and off?

I have my own blog website: Essentially, what I am aiming for is When a user clicks on the search button, a floating semi-transparent textarea window should appear inside the designated rectangle area (as shown in the image, that red orange rectangle). ...

I'm having trouble launching Clinic.js, any suggestions on what steps I should take next?

When starting up your application, use the following command: clinic doctor --on-port 'autocannon -m POST localhost:8000/users/register' -- node dist/main.js If you need help, check out the Clinic.js Doctor - v9.2.0 log. The clinic doctor tool ...

How can I pre-fill an AutoModelSelect2Field with static information in Django using the django-select2 library?

I am currently using a field similar to the one below: class ContactSelect(AutoModelSelect2Field): queryset = Contact.objects.all() search_fields = ['name__contains'] to_field = 'name' widget = AutoHeavySelect2Widget W ...

What steps do I need to follow to set up a Loading screen in Vue3 and Vite correctly?

Is there a better way to handle the loading state for an entire app instead of setting up a Loading screen with a time interval of 2 seconds using a Loading component? The Loading component has been directly integrated into the router-view of App.vue to a ...

Replace Jade script with block override

Having trouble overriding a Jade script. tag, nothing seems to work. Here is the code snippet: Layout.jade block foot footer.container#footer .row .twelve.columns All rights reserved. &copy; 2015 Pet Feeder block scripts ...

Receive a positive or negative data message through Ajax Response

Exploring Ajax for the first time, I am eager to incorporate database interaction using AJAX in JQUERY by connecting to a PHP script. $(function() { $.ajax({ type: "POST", url: "response.php", ...

Node.js Apple in-app purchase (IAP) receipt validation

Trying to implement Node.js from this repository for my IAP Receipt Validation, but encountering an error in the server's log: "The data in the receipt-data property was malformed." Seeking assistance on properly sending a base64 string to Node.js an ...

Transferring a JavaScript variable to a PHP file through jQuery's Ajax functionality

I'm having trouble figuring out how to pass a JavaScript variable to a PHP script using AJAX. This is my first attempt at using AJAX and I seem to be missing something. Here's the code snippet: function selectCategory(value) { $.ajax({ ...

Determine in Typescript if a value is a string or not

In my code, I have a component: export type InputData = string | number | null; interface InputData { data?: string | number | null; validate: boolean; } const App: React.FC<InputData> = ({ data = '', validate = true, }) => ...

Error encountered when attempting to use the submit button in AngularJS

My goal is to create a simple Angular application that takes input of two numbers (n1 and n2) and then prints their sum. I have integrated Bootstrap for styling, but noticed that nothing was happening upon submission. To troubleshoot, I added an alert() fu ...

Utilize ES6 in React to dynamically update state with setState and retrieve state with the

Recently I discovered a technique for handling multiple input events using dynamic state. If I have a state setup like this this.state = { name_1: 'john', name_2: 'james' } I can access my state values like this [1,2].forEach ...

React Intersection Observer Triggering Memory Leaks

Issue Description: I encountered a problem with my React app crashing on mobile. The Chrome dev tools revealed that garbage collection wasn't triggering, and upon inspecting the heap, I found that the top constructors by retained size were all linked ...

Loading data table rows dynamically using Vuetify

I have a Vuetify datatable structured like this <v-data-table :items="items" :headers="headers" :search="search"> <template slot="items" slot-scope="props"> <td>{{props.item.id}}</td> <td& ...

I am experiencing issues with the button click functionality in my Google extension

Greetings! I am currently developing a Chrome extension that will automatically redirect to my website and fill in the password. However, I am facing an issue with submitting the button click event. // Here is my manifest.json code { "name": "z", "v ...