Utilize Vue to have images expand individually upon clicking

Looking to create an image modal using HTML, CSS, and Vue. As a novice in this area, I am facing an issue where clicking on one image enlarges all of them, instead of just the selected one. This is happening because I am looping through an array for the images. How can I modify the code to only enlarge the clicked image while looping through the array?

<div v-if="visible" class="food__menu">
          <a href="#" class="food__list" v-for="food in foods" :key="food">
            <div class="food__image">
              <img
                :src="food.image"
                :class="{fullWidthImage : fullWidthImage }"
                @click="fullWidthImage = !fullWidthImage"
              />
            </div>
            <div class="food__details">
              <span class="food__name">{{food.name}}</span>
              <span class="food__type">{{food.type}}</span>
            </div>
          </a>
        </div>
.fullWidthImage {
  width: 300px !important;
  height: 400px !important;
  display: flex;
  position: absolute;
}

.food__image img {
  height: 60px;
  width: 60px;
}
export default {
  data() {
    return {
      toggle: false,
      visible: false,
      mealTitle: false,
      fullWidthImage: false,
      foods: [
        {
          image: require("../assets/images/food.png"),
          name: "potatoes",
          type: "Carbohydrate"
        },
        {
          image: require("../assets/images/food1.png"),
          name: " rice",
          type: "Protein"
        },
        {
          image: require("../assets/images/food2.png"),
          name: "Lamb",
          type: "Carbohydrate"
        },
}
}
}

Trying to achieve something similar to this, but encountering an issue where all images enlarge when clicked. Any guidance would be appreciated! https://i.sstatic.net/8W126.png

Answer №1

One of the reasons for this behavior is due to storing the fullWidthImage at a component data level, which affects all images instead of individual ones. As a result, when it switches to true, all images become enlarged.

To address this issue, you can store the index of the image you wish to display in full width. This approach enables you to toggle the class conditionally based on the image index.

<a href="#" class="food__list" v-for="(food, i) in foods" :key="food">
    <div class="food__image">
        <img
            :src="food.image"
            :class="getImageClass(i)"
            @click="onImageClick(i)"
        />
    </div>
</a>

To implement this solution, create the following methods within the component:

data: {
    fullWidthImageIndex: null,
    // ... other data here
},
methods: {
    getImageClass: function(i) {
        return {
            'fullWidthImage': this.fullWidthImageIndex === i
        };
    },
    onImageClick: function(i) {
        if (this.fullWidthImageIndex === i) {
            this.fullWidthImageIndex = null;
        } else {
            this.fullWidthImageIndex = i;
        }
    }
}

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

I seem to be having a problem with CSS and Flexbox sizing. Does anyone have an explanation for what might be

Hey there! I'm currently in the process of building a Netflix clone, and everything seems to be working well except for one issue with the layout. No matter how I adjust the width of the div containing the images, they just won't change size. I&a ...

Is there a reason why the integration of OnsenUI with Vue using vue-onsenui and v-ons-segment is not functioning

I am experiencing an issue with OnsenUI and VUE vue-onsenui v-ons-segment. Instead of displaying a button bar in a row as expected, I am seeing standard buttons. The problematic code resides in a customized Monaca CLI project utilizing the minimal VUE tem ...

My approach to using this style in React involves utilizing the class attribute as follows: "class[attribute]" [Updated version 2]

When trying to customize an element based on its attribute, the process is a bit different in React compared to pure CSS. Here's an example: <div class='something' data-test='4'></div> ... .something[data-test] { bac ...

Having trouble updating values in Vue3 when accessing the next item in an object?

I'm attempting to allow my users to browse through a collection of various items. Take a look at the records object below: 0: {id: 1, pipeline_id: 1, raw: '1', completion: null, processed: 0, …} 1: {id: 2, pipeline_id: 1, raw: '2&apo ...

Retrieving Basic HTML Source Code in UITextView Without CSS Styling Using Objective-C

I am looking to make changes to HTML text within a UITextView. The original text was created using an HTML editor in the web version of the app and needs to be edited with a default font on iOS. Here is the simple HTML code for the text that needs editing ...

Is there a way to execute a code snippet just once when focusing on a specific field?

<form id="myForm"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="mname">Middle name:</label> ...

Guiding the jQuery Document

I currently have a stylesheet in the head section with the following content: *, body { direction:rtl; } Upon inspection, I found that the dir variable of jQuery is set to ltr: $(function(){ alert(this.dir); }); How can I obtain the specific page di ...

Utilizing Vue.js to Dynamically Insert Template Text as HTML Element

I need a solution where I have a line like this: This line contains {{input}} as well as {{select}}. This line is fetched from the backend database and my frontend is built using Vue JS 2.6 My goal is to parse the {{input}} and convert it into an HTML in ...

Activate the Jquery slider after the AJAX content has been loaded

I attempted to follow the guidance from another question, but I seem to be struggling with the syntax. Upon clicking a div, it triggers a JQuery call that then executes an AJAX function to load a document. The AJAX request involves fetching some complex c ...

Ways to receive HTTP response from a Lumen API in an asynchronous manner

When using Laravel Lumen, the responses are sent to the client side in the order of requests, with each response waiting for the previous one to complete. To make this process asynchronous, changes need to be implemented. Laravel Lumen Routing Code: $rou ...

How can I effectively utilize find, match, and filter functions with a reactive array in VueJS?

Having some trouble with understanding .value! :) I'm currently working with VueJS v3 and the Composition API. My goal is to locate the first matching value in a reactive array of people. Typically, this array would be populated through an API call, ...

Creating a dynamic routerLink value in Angular 8 for items within an ngFor loop

I am currently attempting to route a dynamic value from the NgFor using [routerLink]. <li class="list-group-item d-flex justify-content-between align-items-center" *ngFor="let factors of factorsList"> <span>{{factors | ...

Content of reusable angular form is not visible on the homepage

I am currently working on creating a reusable Angular form within an Ionic application. Despite following various tutorials and Stack Overflow posts, I have resolved all errors but unfortunately, the content does not display on the parent page. Here is my ...

Is there a way to apply the css blur filter without losing the opacity of the edges?

I'm experimenting with adding a CSS blur filter to an image while keeping the opacity intact. When I test it with a simple blue square image, the edges become transparent and reveal the underlying black div. Is there a way to achieve the blur effect w ...

The "maxfilesexceeded" event in dropzone.js does not seem to be triggered when adding files programmatically

In my Vue.js project, I am using dropzone with the maxFiles: 1 option set. To display an existing file from the server in dropzone, I have added the following code: let mockFile = { name: 'Filename', size: file.size }; myDropzone.emit('added ...

Adjusting the layering of a nested element within a container div using

I am facing an issue with two buttons placed within a container div that is being overlapped by another container div. The bottom container overlaps the top one, rendering the buttons unclickable. I have been trying to find a solution to make the buttons ...

Utilizing the CSS grid framework to efficiently create repetitive rows and columns in code

When I work with CSS frameworks like Bootstrap or Materialize, I often find myself repeatedly typing the same HTML code: <div class="row"> <div class="col s12"> <!-- Some text/ a button / something --> </div> </d ...

Action buttons on material cards extend beyond the boundaries of the card content on both the left and right sides

Check out this Angular 10.2 Material sample where the action buttons on the right and left extend beyond the card-content: https://i.sstatic.net/Btxy1.png The "Create account" button's right edge should align with the right edge of the fields, and t ...

JavaScript's connection to the CSS property visibility seems to be causing some issues

The Javascript code seems to be ignoring the CSS display property, even though it's set in the style sheet. I added a debugger statement and noticed that the display value was empty. I've been staring at this for some time now, so I must be overl ...

Converting Excel values to Exponential format using Python

I'm struggling to find a solution for extracting the Invoice Number in Python from an Excel sheet without turning it into exponential form. Expected Value: 8000030910 Result: 8.00002e+09 Python Result Excel sheet d1.append(sheet.cell_value(j,0)) ...