Aurilie
Aurilie

Reputation: 199

push is not a function when accessing nested array dynamically in Vue.js

What I'm trying to do is when a user uploads some data there will be 2 buttons one is old products and the other is new products. When the user clicks either of those buttons then the products will be uploaded with either 'old_product' or 'new_product'. But when I click on either button I get this error

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

Here is my code

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

Upvotes: 1

Views: 101

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

It should work as tried out below :

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>

Upvotes: 1

Related Questions