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

175
Visualizações
Counter 'localStorage'

in this counter i want to save number in localStorage, tell me what is the error why it is not saved in memory

const app = Vue.createApp({
  data() {
    return {
      counter: 0,
    };
  },
  methods: {
    getItem() {
      localStorage.setItem('count', this.counter);
      return localStorage.getItem('count');
    },
  },
}).mount('#app');
  <div id="app">
      <h2>{{getItem()}}</h2>
      <button @click="counter--">-</button>
      <button @click="counter++">+</button>
    </div>

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

0

The problem here is whenever the page loads, and you call getItem() you reset localStorage.count = 0 since it automatically initializes to 0.

Instead, do something like this:

const app = Vue.createApp({
  data() {
    return {
      counter: localStorage.getItem('count') || 0,
    };
  },
  watch: {
    counter() {
      localStorage.setItem('count', this.counter);
    }

  },
  methods: {
    getItem() {
      return localStorage.getItem('count');
    },
  },
}).mount('#app');

This way, you're setting the initial value to the value from storage; and watching that value for a change and then updating localStorage to reflect the correct value stored across the window.

about 4 years ago · Juan Pablo Isaza Relatório

0

This solution should work for you:

Here is an improved version:

In this solution, I used a ternary operator that asks first if the counter property exists in the local storage if not then the counter will initialize with the value 0, if the counter is there will get the value and parse that value to int value as all value in the local store save as string.

So if you sum the value a string will do the following:

step: 1

counter = '0';

step: 2

counter++

in this step, the counter will parse to an Integer but still be 0;

Instead, if you do what I code

step: 1

counter = parseInt('0');

step: 2

counter++, the counter at the first time will be 1

As this code is for vuejs version 3 the snippet will not work

const app = Vue.createApp({
  data() {
    return {
      counter: localStorage.getItem('count') ? parseInt(localStorage.getItem('count')) : 0,
    };
  },
  watch: {
    counter(newQuestion, oldQuestion){
      localStorage.setItem('count', newQuestion)
    }
  },
}).mount('#app');
<div id="app">
   <h2>{{counter}}</h2>
   <button @click="counter--">-</button>
   <button @click="counter++">+</button>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Use computed properties. So you dont need methods, watchers or data

const app = Vue.createApp({
  computed: {
     counter: {
        get() {
           return localStorage.getItem('count') || 0
        },
        set(val) {
           localStorage.setItem("count", val)
        }
     }
  },
}).mount('#app');
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