javascriptnode.jsvue.jseventstwo-way-binding

problems passing parameters in winds in vue js


I have this code and I get an array in the info variable. The problem is in the delete button that calls the remove function passing the id as a parameter but it passes the first id to all elements so when I delete any element it deletes the first one instead of referring to the button

    <tr>
      <th scope="row">{{info.product_key}}</th>
      <td>{{info.name}}</td>
      <td>{{info.quantities}}</td>
      <td>{{info.quatities_sold}}</td>
      <td>{{info.cost_price}}</td>
      <td>{{info.sale_price}}</td>
      <td><button @click="showEditModal" class="btn btn-warning">editar</button></td>
       <EditProductModal 
       :_id=info._id 
       :product_key=info.product_key
       :product_name=info.name 
       :quantities=info.quantities
       :quantities_sold=info.quatities_sold
       :cost_price=info.cost_price
       :sale_price=info.sale_price
       :categories=info.categories
         />
      <td><button @click="remove(info._id)" class="btn btn-danger">excluir</button></td>
    </tr>
   
  </tbody>```

Solution

  • As you said I get an array in the info variable but looks like instead of iterating you are directly using it. If you are iterating it properly using v-for it should pass the correct ID.

    Working Demo :

    const app = new Vue({
      el: '#app',
      data: {
        info: [{
          '_id': 1, 
          'name': 'alpha'
        }, {
          '_id': 2, 
          'name': 'beta'
        }, {
          '_id': 3, 
          'name': 'gama'
        }]
      },
      methods: {
        remove(itemID) {
            console.log(itemID);
        }
      }
      
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <table>
        <tr v-for="item in info" :key="item._id">
          <td>{{item.name}}</td>
          <td><button @click="remove(item._id)">excluir</button></td>
        </tr>
      </table>
    </div>