Alternative to using require in Vuejs 3 with Vite for an array of images

Currently making the transition to vite with vuejs and facing a particular issue:

While debugging, I have a component that needs to display images from a folder:

imageArray: [
     require ("../ assets / dummies / Mission -1.jpg"),
     require ("../ assets / dummies / Mission -2.jpg"),
     require ("../ assets / dummies / Mission -3.jpg"),
     require ("../ assets / dummies / Mission -4.jpg")
]

Within the component resides the following div:

<div: class = "bgClass" v-if = "isDebug () == true"> </div>

Following this is a dynamic class using computed property which allows for scrolling through the images.

computed: {
     bgClass: function () {
      
       return {
           backgroundImage: 'url (' + this.imageArray [this.imagePos] + ')',
           ...
       }
     }
   }

The 'require' feature is not supported in Vite, and I would prefer not to convert the old vue2 components to the new vue3 composition API.

Is there an easy way to load images into an array and navigate through them in the component?

Answer №1

If you want to easily handle images in your Vite project, follow these steps:

Refer to the Vite documentation for importing assets as URLs

const useImage = ((url) => {
  return new URL(`/src/${url}`, import.meta.url).href;
});

Create a global property in your main.js file:

app.config.globalProperties.$image = useImage;

Then, when you need to use an image URL, simply call it like this:

$image(imageUrl)

Answer №2

When I first started using Vite, I encountered a similar issue that others had faced. After reading advice from fellow developers and conducting some experiments, I came up with an example solution using the v-for directive. Hopefully, this snippet can assist anyone else encountering the same problem.

<template>
    <div
        v-for="item in items"
        :key="item.id"
    >
        <img
            :src="`${imageUrl}${item.image}.jpg`"
            :alt="item.description"
        >
    </div>
</template>
<script>
export default {
    setup() {
        const imageUrl = new URL("../assets/images/", import.meta.url).href;
        return { imageUrl };
    },
    props: {
        items: {
            type: Object,
            default: function() {
                return {};
            },
        },
    },
};
</script>

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

Spinning objects in three.js using tween.js to move around the global axis

Currently, I am working on tween-rotating a 3D cube. Thanks to this helpful post (How to rotate a object on axis world three.js?), I have successfully achieved rotation without any issues. Now, my goal is to transfer the rotation achieved through setFromRo ...

Discover the power of catching Custom DOM Events in Angular

When working with an Angular library, I encountered a situation where a component within the library dispatches CustomEvents using code like the following: const domEvent = new CustomEvent('unselect', { bubbles: true }); this.elementRef.nati ...

Adjusting the width of a product slider based on window size changes using CSS media queries

Currently, I have a functional product slider that I am attempting to adjust the width for smaller viewports, but it is proving to be a challenge. Upon loading the document, the code tallies the width of each product item and initiates slides when buttons ...

Oops! Looks like the connection has been abruptly cut off from the ASYNC node

Is there a way to properly close an async connection once all data has been successfully entered? Despite attempting to end the connection outside of the loop, it seems that the structure is being finalized after the first INSERT operation CODE require( ...

Using AngularJS to send data from a controller to a factory

Looking to implement a basic pagination feature with data from the backend. Each page should display 10 activities. /feed/1 -> displays 0-10 /feed/2 -> displays 10-20 /feed/3 -> displays 20-30 The goal is to start at page 1 and increment the pag ...

Tips for evaluating the outputs of two computed properties in Vue.js

In our application, users can apply to events and we also have blog posts about various events. We want to display all the blog posts related to events that a user has applied to. Each post is associated with an eventId and each application object contain ...

Uploading profile images with AngularJS and Firebase

I am encountering an issue with my JavaScript image uploader. It successfully uploads an image and provides the image src, but I need to save this value in my FireBase DB for the current user that is being created. Initially, I attempted to output the img ...

Is it recommended to place JavaScript/CSS at the bottom of an HTML document?

I am currently utilizing jQuery Mobile, and at the moment, my <head> section looks like this: <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1"> <title>help</title> <link ...

Randomly loading Json files in Ionic is a great way to keep your

I have a div using *ngFor which loads values from a JSON file. I want to load values from different JSON files randomly each time the div is loaded. Is there a way to achieve this using Math.random() or any other methods? html file <div class= ...

Handling events within a Vue 2 component using $(document)

There is a Vue 2 component implemented like below: <template> <section class="component" v-if="load"> ... </section> <div class="loader" v-else> ... </div> </tem ...

The function you are trying to execute in jQuery Mobile is not defined

I'm currently working on creating an external panel, but I've encountered some difficulties. Below is the HTML code: <html> <head> <title>My Page</title> <meta name="viewport" content="width=devi ...

Enhance your Next.js application by including the 'style' attribute to an element within an event listener

I am currently trying to add styles to a DOM element in Next.js using TypeScript. However, I keep getting the error message "Property 'style' does not exist on type 'Element'" in Visual Studio Code. I have been unable to find an answer ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...

Unusual hue in the backdrop of a daisyui modal

https://i.stack.imgur.com/fLQdY.png I have tried various methods, but I am unable to get rid of the strange color in the background of the Modal. Just for reference, I am using Tailwind CSS with Daisy UI on Next.JS. <> <button className='btn ...

Send live information to router-link

I'm struggling to pass a dynamic path to vue-router, but I can't seem to get the syntax right. Here's what I've been attempting: <li v-on:click="$emit('closeDropdown')"><router-link :to="item.route" id="button">{{ ...

Issue with Codemirror lint functionality not functioning properly in a React/Redux/Typescript application

I'm currently working on enabling the linting addon for the react-codemirror package in a React/Redux/TS application. The basic codemirror features like syntax highlighting and line numbers are functioning properly. However, upon enabling linting, I n ...

jEditable: sending TinyMCE data back to textarea

Hey, I've got a mix of TinyMCE jQuery plugin and Jeditable on a textarea. What happens is, when the editable element is clicked it turns into a TinyMCE iframe. Now, my challenge is to get the content from the iframe back to the textarea using tinymce. ...

Is there a way to switch the axes on a bar chart created using eCharts using JavaScript?

After creating a bar chart using eCharts, I want to switch the x and y axes for better visualization. I attempted to swap the data objects for the axes, but that approach did not yield the desired outcome. Unfortunately, my online research did not provide ...

Angular 2 encountered a fatal error: Issues with parsing the template:

Here is the code snippet I am currently working with: <div class="container"> <div [hidden]="loggedIn"> <md-grid-list cols="6" [style.margin-top]="'20px'"> <md-grid-tile [colspan]="1"></md-grid-tile> I have already ...

Utilizing React Hooks to insert components into a div

I am in the process of creating a todo list using React and realized that states are used in React instead of innerHTML or appendChild() in JavaScript. My challenge lies here: When a user clicks on a button, a simple todo should be added to the parent div ...