简体   繁体   中英

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM