Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
Storing an integer variable in local storage in alpine.js

I wanted to store an integer value in local storage using alpine.js

There is a button that increments the value by 1 when pressed.

Here is how I thought it should be:

<div id="greeting" class="inner" x-data="{ $store.integer: 0 }">
    <button class="button bouncy" @click="$store.integer+=1" x-text="$store.integer + ' is the number'"></button>
</div>

<script>
    document.addEventListener('alpine:init', () => 
    Alpine.store('store', integer)
    })
</script>

This didn't work. I tried some other implementations, but none of them seemed to work. I also tried not adding the $store, since it showed the integer as "undefined" when I did that.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Alpine has the persist plugin which looks like it might suit your needs.

https://alpinejs.dev/plugins/persist

<div x-data="{ count: $persist(0) }">
<button x-on:click="count++">Increment</button>

<span x-text="count"></span>
</div>
about 4 years ago · Juan Pablo Isaza Relatório

0

You have a couple of mistakes in the example code. The corrected version is the following:

<div id="greeting" class="inner" x-data="{}">
    <button class="button bouncy" @click="$store.integer += 1" x-text="$store.integer + ' is the number'"></button>
</div>

<script>
document.addEventListener('alpine:init', () => {
    Alpine.store('integer', 0)
})
</script>
  1. When you create a new variable in the store, the first argument is the name of the variable, the second is its initial value.
  2. In the component, you don't have to recreate the variable in the x-data attribute, since it is defined in the alpine:init hook. So you can use just an empty x-data (assuming you don't have other variables in the component).
  3. You have a missing { after =>.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda