How to change Json object?

Asked

Viewed 32 times

1

I’m trying to change the value of this object/property but returns the error of underfined even when I give console.log, I wanted to understand why I can’t get to it. - HTML

<li v-for="item in items">
      {{item.name}} - {{item.Qtd}}
       <input type="button" value="+" @click="AdicionarQtd()">
       <input type="button" value="Remover Item" @click="removerItem">
       <span v-if="!(item.Qtd >0)">Fora de estoque</span>
     </li>

-Method

 AdicionarQtd: function(item){
                this.item.Qtd+=1;
            }

Json

items: [{
            name:'caneta',
            Qtd:5,
        }],
  • In the method you did not pass the item and the function called itself variable of its scope. It will not really work

1 answer

0

In your code, it has not been specified which item will be changed in the Qtd and in the exclusion also was not passed the item that should be excluded, example:

<input type="button" value="+" @click="AdicionarQtd(item)">
<input type="button" value="Remover Item" @click="removerItem(item)">

notice that both of us input type button in the function is passed the collection item, and this helps you in the individual changes and deletion summary of the item.

Code:

new Vue({
      el: "#lista",
      data: function() {
        return {
          items: [{
              name: 'caneta',
              Qtd: 0
            },
            {
              name: 'lapis',
              Qtd: 2
            },
            {
              name: 'borracha',
              Qtd: 3
            }
          ]
        }
      },
      methods: {
        AdicionarQtd: function(item) {
          item.Qtd++;
        },
        removerItem: function(item) {
          const index = this.items.indexOf(item);
          this.items.splice(index, 1);
        }
      }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="lista">
  <li v-for="(item, index) in items" v-bind:key="index">
    {{item.name}} - {{item.Qtd}}
    <input type="button" value="+" @click="AdicionarQtd(item)">
    <input type="button" value="Remover Item" @click="removerItem(item)">
    <span v-if="(item.Qtd === 0)">Fora de estoque</span>
  </li>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.