Showing the chosen picture in a pop-up window

I developed a user-friendly application using Vue.js that allows users to explore books by selecting author names. I implemented a modal to showcase the books, but encountered an issue where clicking on different cards displayed the same image repeatedly. I attempted to resolve this problem by incorporating a loop with the following code:

    <div class="modal" v-for="item in card">
        <img v-bind:src="item.img" class="book-enlarge" alt="book" />
    </div>

Below is my HTML code snippet:

    <div
        v-show="author === '' || author === item.author"
        :class="{ active: author === item.author }"
        v-for="(item, index) in card"
        v-bind:data-index="index + 1"
        @click="showModal(index)"
    >
        <img v-bind:src="item.img" alt="book" class="card__book" />
        <div class="card__body">
            <h1 class="card__title">{{ item.title }}</h1>
            <p class="card__author">
                <span class="card__author--mod">By:</span>
                {{ item.author }}
            </p>
            <p class="card__release">
                <span class="card__release--mod">Release Date:</span>
                {{ item.release }}
            </p>
        </div>

        <form v-bind:action="item.link" target="_blank">
            <input class="btn" type="submit" value="Buy on Amazon" />
        </form>
    </div>

    <div class="overlay" id="overlay">
        <div ref="close" @click="close" class="overlay__close">
            &#8855;
        </div>
        <div class="modal" v-for="item in card">
            <img v-bind:src="item.img" class="book-enlarge" alt="book" />
        </div>
    </div>

Here's how I structured my Vue.js code:

const cardDescriptions = [
  {
    img: '../books-img/book-1.jpg',
    title: 'A Life on Our Planet: My Witness Statement and a Vision for the Future',
    author: 'David Attenborough',
    release: '2020-10-01',
    link: 'https://www.amazon.co.uk/Life-Our-Planet-Witness-Statement/dp/1529108276/ref=sr_1_1?dchild=1&keywords=a+life+on+our+planet&qid=1610306225&quartzVehicle=45-608&replacementKeywords=a+on+our+planet&sr=8-1',
  },
  {
    img: '../books-img/book-2.jpg',
    title: 'Life on Air',
    author: 'David Attenborough',
    release: '2010-05-20',
    link: 'https://www.amazon.co.uk/Life-Air-David-Attenborough/dp/1849900019/ref=sr_1_1?dchild=1&keywords=life+on+air&qid=1610306334&quartzVehicle=45-608&replacementKeywords=on+air&sr=8-1',
  },
  {
    img: '../books-img/book-3.jpg',
    title: 'HTML, CSS and JavaScript in easy steps',
    author: 'Mike McGrath',
    release: '2020-08-06',
    link: 'https://www.amazon.co.uk/HTML-CSS-JavaScript-easy-steps/dp/184078878X/ref=sr_1_1?dchild=1&keywords=HTML%2C+CSS+and+JavaScript+in+easy+steps%3A+%28In+Easy+Steps%29&qid=1610306384&sr=8-1',
  },
  {
    img: '../books-img/book-4.jpg',
    title: 'HTML5 in easy steps, 2nd edition',
    author: 'Mike McGrath',
    release: '2017-02-17',
    link: 'https://www.amazon.co.uk/HTML5-easy-steps-Mike-McGrath/dp/1840787546/ref=sr_1_1?dchild=1&keywords=HTML5+in+easy+steps%3A+%282nd+edition%29&qid=1610306431&sr=8-1',
  },
];

new Vue({
  el: '#container',
  data: {
    card: cardDescriptions,
    author: '',
  },
  methods: {
    displayBooks: function (e) {
      this.author = e.target.value;
    },
    showModal: function (index) {
      document.querySelector('#overlay').style.display = 'block';
      console.log(index + 1);
    },
  },
  computed: {
    filteredNames: function () {
      const authors = [];
      this.card.forEach(item => {
        if (!authors.includes(item.author)) {
          authors.push(item.author);
        }
      });
      return authors;
    },
  },
});

new Vue({
  el: '#overlay',
  data: {
    card: cardDescriptions,
  },
  methods: {
    close: function () {
      const closeModal = this.$refs.close.parentNode;
      closeModal.style.display = 'none';
    },
  },
});

If anyone could provide assistance with this issue, it would be highly appreciated!

Thank you in advance!

Answer №1

Your demonstration still includes two instances of Vue.

To properly utilize the require function, follow this format:

<img v-bind:src="require`@/assets/${item.img}`" alt="book" class="card__book" />

The symbol @ represents the root of your src folder, and a static string is required for the require function to function correctly.

Additionally, it's necessary to assign a key to your v-for loop so that Vue can distinguish between unique elements:

<div class="modal" v-for="(item, index) in card" :key="index">
    <img v-bind:src="item.img" class="book-enlarge" alt="book" />
</div>

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

What are your thoughts on integrating PusherJS with Vue 3?

Looking for a way to track pusher events and automatically update the local state or refresh a component. This is my current method of monitoring pusher notifications: ... methods: { refreshSlider() { const pusher = new Pusher(process.env.VUE_AP ...

`req.user` seems to be unresolved, but it is actually defined

Currently, I am working on developing an Express.js application that utilizes Passport.js for authentication in an administration panel. The program is functioning correctly at the moment, with my app.js initializing passport and setting up sessions proper ...

How can I retrieve the name of an HTTP status code using JavaScript and AngularJS?

My web application is built using AngularJS, JS, JQ, HTML5, and CSS3. It interacts with our projects' REST API by sending various HTTP methods and manipulating the data received. The functionality is similar to what can be achieved with DHC by Restlet ...

To effectively execute a JQuery / Javascript function, it is essential to incorporate both $(document).ready and $(document).ajaxSucces

I have a JavaScript function that is used for basic UI functionality across my site. Some elements affected by this function are injected via Ajax, while others are static HTML. Currently, I have duplicated the function and applied it to both $(document). ...

Capture the responseBody data within a Newman script from a Postman collection and save it to a

I'm trying to execute a script.js using newman with a locally saved postman collection. The call is successful in postman, returning a token in the response body that I need to access. I would prefer not to open postman every time just to get the res ...

Tips for displaying the message "{"POWER":"ON"}" within the else if statement (this.responseText == ({"POWER":"ON"})) {

Hey everyone, I'm trying to adjust the color of a button on my webpage based on the response I receive from this.responseText. I understand the JSON response, but for some reason, I can't seem to incorporate it into my code. If anyone could lend ...

Invoking a function from a higher-level parent scope within multiple layers of nested directives

I am working with a data structure that is nested infinitely. There is a top-level object containing a collection of objects, and each of these objects can also have their own collection of objects. To iterate through this tree, I have implemented the fol ...

When invoking an external API within a Firebase Cloud Function, it may result in a

I've been attempting to use a basic API for currency conversion within a Firebase Cloud Function written in Typescript, but I keep getting a 'null' response. import { https } from 'firebase-functions'; import * as axios from ' ...

The process of uploading a React App to Heroku resulted in a critical error: "FATAL ERROR: Heap limit reached, Allocation failed - JavaScript heap out of memory."

There's a puzzling issue that I believe I have the solution to (paying for more bandwidth on Heroku), but the root of the problem eludes me and it's truly frustrating. Any assistance in pinpointing the cause would be greatly appreciated! Hopefull ...

Adding personalized typings to a JHipster (v5.82) application

Starting a new JHipster project (v5.8.2) and integrating the Metronic Angular theme can be a bit of a challenge, especially with limited documentation available. After integrating the various css/js bundles and components, I encountered an issue with some ...

The contrast between utilizing Vue Router's replace function and route redirect feature within the Vue Router

I am a beginner in Vue.js and I'm trying to understand the distinction between using Router replace and route redirect in my project. Can someone please explain how to properly utilize them? ...

Modifying the CSS based on the SQL data retrieved

I'm currently diving into the world of php and jquery, attempting to build a webpage that displays player information and their status fetched from my Mysql server. Although the core code is functional, it's a mashup of snippets gathered from va ...

Navigating within a class-based component using Next.js: A brief guide

Is it possible to create a redirect from within an onSubmit call while maintaining CampaignNew as a class-based component? I have provided the code snippet below, and I am looking for guidance on achieving this. import React, { Component } from "rea ...

Is npm create-react-app giving you trouble?

When attempting to create a React app using the command npm create-react-app appname, the tool would just return me to the same line to input more code. I also gave npx a try, but encountered some errors in the process. See this screenshot for reference: ...

Removing duplicate elements within a parent div using jQuery

I'm looking to eliminate duplicate elements of the same class within a parent div. I tried using the code below, but it ends up removing all elements except the first one. let found = {}; $('.product-bottom').each(function(){ let $this ...

How can I prevent Bootstrap from disrupting my CSS layout and what steps can I take to rectify the issue?

Apologies for any language mistakes, as this is my third language and I am new to web design. I want to create a simple website using html, css, and bootstrap that does not need to be responsive. I have successfully added a sticky Navbar with javascript ...

Adjust the background color of a cell depending on its value - Implementing with VueJs and Vuetify

I am currently extracting data from a JSON file. My goal is to change the cell color to green if the value is "OK" and to red if the value is "KO". Currently, I have implemented a v-simple-table as shown below: <td :class="OK? 'primary' : &apo ...

A guide to efficiently managing updates and inserts with bulkCreate in node.js

Currently, I am utilizing node.js to facilitate the uploading of an excel file into a database. Furthermore, in my service, I am employing bulkCreate to efficiently upload the data into the mysql db. In order to provide more context, I will outline the str ...

What is the reason behind Vue not updating the array order in $ref when unshift is used?

Here's an interesting example to ponder: <template> <div> <button @click="addItem">Add Item</button> <h1>Fruits</h1> <ul> <li v-for="(item, index) in items" ...

Using Node.js and Express to assign a JavaScript property to a variable

Feeling a bit lost here, struggling with the "too noob to know what to search for" syndrome. In my Node/Express app, I'm attempting to retrieve user information from a mySQL DB and pass the user's email to an Infusionsoft API. When I hardcode th ...