The parameters for Vue.js @change events are consistently returning as 0 whenever a file is uploaded by clicking on the picture

Check out my JSFiddle here:: https://jsfiddle.net/includephone/o9gpb1q8

I've encountered an issue involving the @change event on an input field. My goal is to create a carousel of images with 4 images per slide.

Data Object Structure

 data: function () {
        return {
            page: [
                {
                    type: 'text',
                    name: 'title-brand',
                    text: '',
                    image: '',
                    preview: ''
                },
                {
                    name:'slider',
                    type:'file',
                    slide:[
                        [
                            {
                                model_name:'',
                                inst:'',
                                item_name:'',
                                item_link:'',
                                image:'',
                                preview:''
                            },
                            {
                                model_name:'',
                                inst:'',
                                item_name:'',
                                item_link:'',
                                image:'',
                                preview:''
                            },
                            {
                                model_name:'',
                                inst:'',
                                item_name:'',
                                item_link:'',
                                image:'',
                                preview:''
                            },
                            {
                                model_name:'',
                                inst:'',
                                item_name:'',
                                item_link:'',
                                image:'',
                                preview:''
                            }
                        ]
                    ],
                }
            ]
        }
    },

Methods I'm Using

methods: {
        onImageChange(e, parent_index, index, item_index){
            let files = e.target.files || e.dataTransfer.files;
            let vm = this.page[parent_index];
            console.log(`${index}, ${item_index}`);
            let reader = new FileReader();
            reader.onload = (e)=> {
                Vue.set(vm.slide[index][item_index], 'image', e.target.result);
            }
            Vue.set(vm.slide[index][item_index], 'preview', URL.createObjectURL(files[0]));
            reader.readAsDataURL(files[0])
        },
        stat(par1, par2){
            console.log(`pat1: ${par1}, par2: ${par2}`);
        }
}

Template for Data Display

<div v-for="(component, parent_index) in page" v-bind:key="parent_index" class="container-constructor">
    <div v-if="component.name==='slider'" class="data-block slider">
        <div class="body-block">
            <div v-for="(slide, index) in component.slide" v-bind:key="index">
                <div v-for="(item, item_index) in slide" v-bind:key="item_index" class="slider-item">
                    <button type="button" @click="stat(index, item_index)">Click {{index}} {{item_index}}</button>
                    <label for="slider-item-file-1">
                        <img v-if="item.preview.length>1" :src="item.preview" width="160px" height="200px"/>
                        <img v-else src="images/image6.png" width="160px" height="200px"/>
                    </label>
                    <input type="file" @change="onImageChange($event, parent_index, index, item_index)" id="slider-item-file-1"/>
                    <div class="slider-item-info">
                        <input type="text" v-model="item.model_name" name="model-name" placeholder="model name"/>
                        <input type="text" v-model="item.inst" name="instagram-model" placeholder="model inst"/>
                        <div class="item-name">
                            <input type="text" v-model="item.item_name" name="item-name" placeholder="item name"/>
                            <input type="text" v-model="item.inst" name="item-link" placeholder="item link"/>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Has anyone experienced issues with passing parameters correctly, as mine always seem to be 0 when loading? Any insights on how to resolve this?

Answer №1

The issue with item_index always being 0 stems from the fact that the label assigned to the image is tied to the generic id slider-item-file-1, which is applied to every file input element. To resolve this, each element should have a unique id. Currently, your code lacks this uniqueness, causing the click on the label to target the first occurrence of that id in the document body, resulting in item_index consistently returning as 0. Modifying the ids dynamically can rectify this dilemma.

This explains why clicking on the bottom image causes it to jump to the top of the page - it navigates to the initial file input with the specified id.

<label :for="'slider-item-file-' + parent_index + '-' + index + '-' + item_index">
      <img v-if="item.preview.length>1" :src="item.preview" width="160px" height="200px"/>
      <img v-else src="images/image6.png" width="160px" height="200px"/>
</label>
<input type="file" @change="onImageChange($event, parent_index, index, item_index)" :id="'slider-item-file-' + parent_index + '-' + index + '-' + item_index"/>

Each id will now include the corresponding index value from the for loop.

I trust this provides clarification.

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 is the optimal location for storing component fetch logic?

When should I make a REST request to retrieve data for a Vue component called Page, specifically for the properties title and content? Also, where is the best place to handle this logic? Currently, I am trying to fetch the data on the component's rea ...

What is the most efficient way to retrieve the operating system's name and version using JavaScript?

I'm in the process of developing an object that will simplify accessing browser and system information by implementing a function. One particular function within this object is responsible for retrieving the operating system name and version, returnin ...

JavaScript Class vs Function as Definition

Having trouble locating documentation for this issue. I devised a JavaScript class in the following manner: class Polygon { constructor(height, width) { this.height = height; this.width = width; } area = function() { return this.height ...

effortlessly eliminate the Google MyMap watermark from an iframe using ReactJS

I am new to ReactJS and I would like help on how to hide the watermark on a Google My Map. Can someone please assist me with this? <iframe src="https://www.google.com/maps/d/u/1/embed?mid=1OMSkPKZi-U-CnmBr71zByNxp8HYi-vOc&ehbc=2E312F" fram ...

Unable to display image in jqGrid binary format

In our system, we use a standard function to retrieve images stored as binaries in the database, and this function works seamlessly throughout the entire system. However, when implementing jqGrid, I encountered difficulties using the existing structure as ...

Combining Javascript and Django for a powerful web development solution

Having trouble setting up JS on my Django web app, despite reading through the documentation and previous queries. Using the Django dev server with the following file structure: mysite/ __init__.py MySiteDB manage.py settings.py ...

Error in Next.js: react-dom.development.js?ac89:14906 - Hook call is invalid. Hooks should only be used within a function component's body

Here is the code snippet I am working with: <div onClick={(e) => handleClick()}>Join Us</div> This is the handleClick function in my code: const handleClick = () => { console.log(Lang.getLocale()) }; And this is the Lang class metho ...

Eliminate numerous items from an array containing objects

Looking for a way to remove specific objects from an array of objects within another object. I want to delete multiple items simultaneously, but when attempting with splice, it shows up as undefined. This is the snippet of code I'm working with: ...

The change handler of the TS RadioGroup component, instead of returning an array of possible strings, returns a unique

My interface declaration for StopData is shown below: export interface StopData { stopName: string, stopType: 'stop' | 'waypoint' } I have implemented a radio group to choose the 'stopType', which consists of two radi ...

React Hooks: Unable to re-enable input after it has been disabled

Attempting to manage the status of my points input whether it's enabled or disabled, I encountered an issue. Upon checking the checkbox, it correctly gets disabled. However, upon unchecking it, the input remains disabled. Initially, I attempted settin ...

How can you display a doughnut chart with a custom color to represent empty or no data, including doughnut rings?

I have integrated a doughnut chart from chartjs into my Vue project using vue-chartjs. Currently, the doughnut chart does not display anything when there is no data or all values are empty. Is there a way to customize the color and show the entire doughnu ...

Troubleshooting V-model errors within VueJS components

Just dipping into VueJS and trying out a chat feature from a tutorial. I noticed the tutorial uses v-model in a component, but when I replicate it, the component doesn't display on the screen and the console throws a "text is not defined" error. Strug ...

Tips for refreshing Vue.js component content using methods?

I am currently facing an issue with re-initializing some input data within my component using a method. Despite being confident in the correctness of the syntax, I encounter an error during code compilation. Can anyone spot the error or provide an explanat ...

Transferring information from the main function to getServerSideProps

I've been facing challenges while trying to pass data from a function component to the getServerSideProps method in Next.js. As a beginner in learning Next.js, I am struggling to understand this concept. My approach involves using context from _app, b ...

What impact does reducing the window size have on my header?

While working on a website with a navigation bar, I encountered an issue where the navbar was not responsive. When the window size was reduced, the nav bar shifted to an awkward position vertically, as shown in the first image. The navbar shifts below the ...

Opinions on crafting a new gadget?

I will only provide each website interested in my widget with the code to copy and paste once. It is crucial that the code is future-proof. After much consideration, this is the widget code I have developed: <script type="text/javascript" src="http:/ ...

Issues with running Vue commands have been reported in Git-Bash, however they seem to work fine in

Whenever I check the version of Vue in my Terminus bash by running vue --version, here's the output I receive: $ vue -v /bin/sh: /Users/kirkb/AppData/Local/Yarn/bin/../Data/global/node_modules/.bin/vue: No such file or directory In PowerShell, when I ...

What is the reason for labels appearing inside select boxes?

Can someone help me understand why my select box label is displaying inside the select box? For example, when I am not using react-material-validator it looks like this: https://codesandbox.io/s/5vr4xp8854 When I try to validate my select box using the r ...

Tips for confirming a sub string is present in an array using JavaScript/TScript

I am currently testing for the presence of a SubString within an array. In my test, I am asserting using: expect(classList).toContain('Rail__focused') However, I encountered the following error: Error: expect(received).toContain(expected // inde ...

Utilizing jQuery to update dropdown selection based on JSON object values

In my JSON value, I have the following roles: var roles = { "roles":[ {"role_id":2,"role_name":"admin"}, {"role_id":4,"role_name":"QA"}, {"role_id":3,"role_name":"TL"}, {"role_id":5,"role_name":"user"}, {"role_id":1,"role_name":"r ...