"Encountering an error in Vue.js when trying to dynamically access nested arrays: push function not

My goal is to have two buttons displayed when a user uploads data: one for old products and one for new products. When the user clicks on either button, the corresponding products will be uploaded as 'old_product' or 'new_product'. However, I encountered an error when attempting this:

_this.product[value].push is not a function

Below is the code snippet:

<template>
  <div>
    <input type="file" class="product_upload" id="product_upload" @change="previewFiles">

    <button type="button" class="btn btn-primary" @click=uploadProduct('new_product')>New Product</button>
    <button type="button" class="btn btn-primary" @click=uploadProduct('old_product')>Old Product</button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        product: {
          old_product: [],
          new_product: []
        }
      }
    },
    methods: {
      previewFiles(event){
        return event.target.files;
      },
      uploadProduct(value){
        let files = this.previewFiles;
        
        this.product[value].push(files);
      }
    }
  }
</script>

Answer №1

Here is the code snippet for your reference:

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',

  data() {
    return {
      files: [],
      product: {
        old_product: [],
        new_product: []
      }
    }
  },
  methods: {
    previewFiles(event) {
      this.files = event.target.files;
    },
    uploadProduct(value) {


      this.product[value].push(this.files);
    }
  }
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">

  <div>
    <input type="file" class="product_upload" id="product_upload" @change="previewFiles"/>

    <button type="button" class="btn btn-primary" @click=uploadProduct('new_product')>New Product</button>
    <button type="button" class="btn btn-primary" @click=uploadProduct('old_product')>Old Product</button>

    <pre>
  {{product}}
  </pre>
  </div>


</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

Ajax: Why am I receiving an error response instead of a successful one?

It's puzzling why my code is triggering the error function instead of success. The console.log keeps showing me this: Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: f ...

What is the process for obtaining a client-side cookie using next.js?

I'm currently facing an issue where I can't seem to maintain a constant value for the isAuthenticated variable between server-side and client-side in next.js. In my setup, I am using a custom app.js file to wrap the app with Apollo Provider. The ...

Encountered an error in React where the declaration file for a module could not be located

New to Typescript and trying to incorporate a splitter into my project. I'm utilizing SplitPane from "react-split-pane/lib/SplitPane" and Pane from "react-split-pane/lib/Pane" in my Typescript project, but encountering an error: Could not find a de ...

Incorporating CSS animations into Vue.js while an API call is being made

When a specific icon is clicked, an API call is triggered: <i class="fas fa-sync" @click.prevent="updateCart(item.id, item.amount)"></i> I am looking to add an animation to rotate the icon until the API call is complete or ...

"Extracting information from a database in Angular Laravel to create a Chart.js display - a step-by-step

Currently, I am working on developing a dashboard application that includes various charts. My aim is to customize the data displayed in each user's chart based on information retrieved from a database. This is how my setup looks like: HTML <div ...

Definitions that are displayed dynamically when hovering over a particular element

I am seeking a way to implement popup definitions that appear when a div is hovered over. My website showcases detailed camera specifications, and I want users to see a brief definition when they hover over the megapixel class called '.mp'. One o ...

Encountering an issue when deploying a project using node, webpack, express, and mysql to Heroku. The error message states: "Uncaught ReferenceError: regeneratorRuntime is not

I've been going around in circles ever since I started this project, and now the code is all over the place. This is my first time working on a node project without using a framework, and I'm starting to regret not choosing PHP. Anyway, here&apos ...

Verify in JavaScript if the script is executing within a WinStore (WinJS) program

I am in the process of developing a JavaScript library that is compatible with both Windows Store (WinJS) applications and traditional HTML/JavaScript apps. The dependency I am utilizing loads dynamically and has separate SDKs for WinJS apps and standard w ...

Express-Session Object Method

I am currently facing an issue with linking an object to an Express session. Below is the code I am using: var express = require('express'); var session = require('express-session'); // Defining an object named "engine" which simulate ...

Tips for modifying a request api through a select form in a REACT application

Apologies if this question seems a bit basic, but I need some help. I am working on creating a film catalog using The Movie Database API. I have successfully developed the home and search system, but now I am struggling to implement a way to filter the fi ...

The overlappingmarkerspidifier is throwing an error because it is unable to access the property '__e3_' of an undefined variable

I am attempting to implement the overlapping marker spidifier feature in my code. I followed the instructions provided in this link: functioning code of oms However, upon creating the OverlappingMarkerSpiderfier object, I encounter the error: Uncaught Typ ...

Tips for avoiding a form reload on onSubmit during unit testing with jasmine

I'm currently working on a unit test to ensure that a user can't submit a form until all fields have been filled out. The test itself is functioning correctly and passes, but the problem arises when the default behavior of form submission causes ...

Challenges with Filtering in MongoDB

I can't seem to figure out what's going wrong with my code. I've checked the documentation and it all appears to be correct. I've also gone through several posts and attempted various solutions. Code: router.get('/rank/:rank' ...

What causes the scrollbar to not extend to the bottom when connected to another scrollbar via a JavaScript equation?

I have been working on a code that involves multiple scrollbars that are all linked together. When you move one scrollbar, the other two will move proportionally. However, due to differences in width, the scroller doesn't always reach the end of the s ...

Having difficulty handling file data following the import of an Excel file in Laravel 5.8

I have a requirement to send multiple emails at once by importing an Excel file. Currently, I am successfully importing the Excel file and storing the data in a variable as an array. I am utilizing maatwebsite/excel version 3.1 for this task. However, afte ...

What is the best way to secure videos and other static files with authentication in a next.js web application?

My goal is to provide static content, specifically videos, exclusively to authorized visitors. I want to secure routes so that they are only accessible to authenticated users. However, the challenge arises when trying to display a video on a page located i ...

A step-by-step guide on including chess.js in your Create React App

I'm facing an issue while trying to incorporate the chess.js npm library into my Create React App. The error message "Chess is not a constructor" keeps popping up. Below is the code snippet I am using: import React from 'react'; import &apos ...

JavaScript is sending a variable to a .php file, which then returns data based on the variable. The information is displayed using JavaScript and AJAX, along with triggers set using the bind('input', function

Currently, I am attempting to create a form that automatically populates some input fields when there is a change. However, I am struggling to understand how to send the #url field to my PHP script. Any insights or suggestions would be greatly appreciated. ...

There was a failure to establish a Redis connection to the server with the address 127.0.0.1 on port 6379

Currently, I am working with node.js using expressjs. My goal is to store an account in the session. To test this out, I decided to experiment with sessions by following the code provided on expressjs var RedisStore = require('connect-redis')(ex ...

Toggle the sidebars to slide out and expand the content division using JavaScript

I am looking to achieve a smooth sliding out effect for my sidebars while expanding the width of the middle content div. I want this action to be toggled back to its original state with another click. Here's what I've attempted so far: $(' ...