Search code examples
javascriptvue.jsv-for

Do I need Vue.set() in order to change value of a data object?


I understand that Vue.set() is used to add reactive properties to an object.

But how would I change the value of an object property. Is this the correct way?

Note: This data change is intended to be sent to the database

Template

 <div class="buttonList" v-for="(expense, index) in expenseButton" :key="index">
    <button type="button" @click="expenseButtonClick(expense)">{{expense.expensesKey}} </button>
    <input class="textInput" v-model.number="expense.subExpense" type="number" />
</div>
data(){
   expenseButton[{
expenseKey: rent,
expenseValue: 10,
subExpenses: ''
}]

}

methods: {
    expenseButtonClick(expense) {
      expense.expensesValue = expense.expensesValue - expense.subExpense;
      console.log(expense);
    }
}

Solution

  • You need to use Vue.set only when you need to add a new property to an object and want it to be reactive. You don't need it when changing an existing property's value.

    FYI, you also need to use Vue.delete only when deleting a property from an object to ensure the view gets updated.