Skip to content
Advertisement

How can i do a iteration whit last value in Alpine JS?

It´s possible to make a sum using the current value and the previous value to generate a new column in the table, in an Alpine iteration?

In code below:

    <template x-for="movimento in movimentos" :key="movimento.id">
      <tr>  
         <td class="border-dashed border-t border-gray-200 text-center Data">
            <span class="text-gray-700 px-1 py-0" 
            x-text="movimento.data"></span>
         </td>
         <td class="border-dashed border-t border-gray-200 text-right Valor">
            <span class="text-gray-700 px-1 py-0" 
            x-text="movimento.valor"></span>
          </td>
          <td class="border-dashed border-t border-gray-200 text-center Tipo">
            <span class="text-gray-700 px-1 py-0" 
            x-text="movimento.tipo"></span>
          </td> 
         <td class="border-dashed border-t border-gray-200 Descricao">
            <span class="text-gray-700 px-1 py-0 items-center" 
            x-text="movimento.descricao"></span>
         </td> 
         <td class="border-dashed border-t border-gray-200 Categoria">
          <span class="text-gray-700 px-1 py-0 items-center" 
          x-text="movimento.categoria"></span>
        </td>
        <td class="border-dashed border-t border-gray-200 Conta">
          <span class="text-gray-700 px-1 py-0 items-center" 
          x-text="movimento.conta"></span>
        </td> 
        <td class="border-dashed border-t border-gray-200 Caixa">
          <span class="text-gray-700 px-1 py-0 items-center" 
          x-text="movimento.caixa"></span>
        </td>                                                             
         <td class="border-dashed border-t border-gray-200 Empreendimento">
           <span class="text-gray-700 px-1 py-0 flex items-center" 
           x-text="movimento.empreendimento"></span>
         </td>                              
      </tr>                           
    </template>

After code:

<td class="border-dashed border-t border-gray-200 text-right Valor">
    <span class="text-gray-700 px-1 py-0" 
        x-text="movimento.valor"></span>
</td>

i need to show balance (current .valor + last .valor) in a new column of my table.

Is this possible?

Thanks for all.

Advertisement

Answer

x-for has a way to access the current item’s index, so we can access the previous item using collection[index - 1]

<template x-for="(movimento, index) in movimentos" :key="movimento.id">
  <tr>
    <td>Current: <span x-text="movimento.valor"></span></td>
    <td>Previous: <span x-text="movimento[index - 1] && movimento[index - 1].valor"></span></td>
    <td>Sum: <span x-text="movimento.valor + (movimento[index - 1] && movimento[index - 1].valor)"></span></td>
  </tr>
</template>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement