Search code examples
javascriptarraysvue.jsv-for

How can I update properties of a data object based on user input?


I have a simple problem that I can seem to solve. Here is the object I am looking to manipulate:

 [ { "expensesKey": "x", "expensesValue": 100, "subExpense": null },
   { "expensesKey": "y", "expensesValue": 100, "subExpense": null }, 
   { "expensesKey": "z", "expensesValue": 100, "subExpense": null } ], 
   "earnings": 300 } ]

I have a v-for loop that has a v-model to bind to the "subExpense" property like so:

div v-for="(expense, index) in expenseButton" :key="index">
     <input placeholder="expense.expensesKey" v-model.number="expense.subExpense"> </input>
</div>

Problem: How can I subtract the "expensesValue" value and subtract the "earnings" value whenever the "subExpense" value changes from the user input?

Attempts:

  1. I created a button with a method that can do this with a click method
  2. A computed method to add up all "subExpense" to subtract from "earnings"
 methods: {
  subtractExpensesValue(expense) {
      expense.expensesValue = expense.expensesValue - expense.subExpense;
      console.log(expense.expensesValue);
    }
},
  computed: {
    addSubExpense() {
      return this.expenseButton.reduce((acc, curr) => {
        acc += Number(curr.subExpense);
        return acc;
      }, 0);
    }
  }


Solution

  • You could modify your button’s method and attach it to the input event of the subExpense input like this:

      v-on:input="substractExpensesValue($event, expense)"
    
    
      subtractExpensesValue(event, expense) {
        expense.expensesValue = expense.expensesValue - expense.subExpense;
        console.log(expense.expensesValue);
      }
    

    Suggestion

    Also you should change your placeholder mapping to :placeholder=“expense.expenseKey” otherwise you just assigned the text to the placeholder. Note the :