Search code examples
arraysvue.jsvuejs2vue-componentv-for

How to target only the last item in a v-for array?


I have an array of objects inside v-for to create a component for each item like so:

<div v-for="(expense, idx) in myExpenses" :key="idx">
  <expense-panel
     v-model.number="expense.expensesValue"
     :expense="expense"
     :myExpenses="myExpenses"
     :showEdit="showEdit">
   </expense-panel>
</div>

I have a method to add and extra "expense" to the array:

(I logged the item I am trying to specifically target)

 addExpense() {
      this.myExpenses.push({
        expensesKey: "",
        expensesValue: null,
        subExpense: null,
      });
//The last item in the array
      console.log(this.myExpenses[this.myExpenses.length - 1]);
    },

Is there a way in Vue to specifically add an input element to the last item of the array?

I have a showInput = false in the parent's Data() already.


Solution

  • You could for example add a slot to expense-panel and conditionally render your-input there only if it's the last item that is being rendered, like this:

    <div v-for="(expense, idx) in myExpenses" :key="idx">
      <expense-panel
         v-model.number="expense.expensesValue"
         :expense="expense"
         :myExpenses="myExpenses"
         :showEdit="showEdit">
         <your-input v-if="idx === myExpenses.length - 1" />
       </expense-panel>
    </div>
    

    Other alternative could be passing a prop to the panel (like is-last) and baking the input into the expense-panel.

    Also, if the input should be rendered visually AFTER the last item, you can simply add input after the whole list:

    <div v-for="(expense, idx) in myExpenses" :key="idx">
      <expense-panel
         v-model.number="expense.expensesValue"
         :expense="expense"
         :myExpenses="myExpenses"
         :showEdit="showEdit">
       </expense-panel>
    </div>
    <your-input />