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

282
Visualizações
Composition API watch handler

How do I refactor this:

watch: {
    count: {
      handler (v) {
        if (v) this.intervalId = setInterval(() => { this.now++ }, 1000)
        else clearInterval(this.intervalId)
      },
      immediate: true
    }
  }

Into Composition API?



I tried something like that, which throws errors:

watch(()=> {
      count.value,
      handler (value) {
      if (value)
        intervalId.value = setInterval(() => {
          now.value++;
        }, 1000);
      else clearInterval(intervalId.value);
      },
      immediate: true
      })
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can refactor it as below. You can pass immediate option to the watch method as the 3rd parameter in Vue 3

const app = Vue.createApp({
  setup() {
    const count = Vue.ref(0);
    const now = Vue.ref(0);
    const intervalId = Vue.ref(0);

    Vue.watch(count, (currentValue, oldValue) => {
      if (currentValue) intervalId.value = setInterval(() => now.value++, 1000);
    }, {
      immediate: true
    });
    
    Vue.onUnmounted(() => { clearInterval(intervalId.value) });

    return {
      count,
      now
    };
  }
}).mount('#app');
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
  {{ count }} - {{ now }}
  <button @click="count++">Increment</button>
  <button @click="count=0">reset</button>
</div>

Reference:
  • Composition API - Lifecycle hooks

P.S: You can use import {watch, ref, onUnmounted} from "vue" to make the code cleaner.

over 4 years ago · Santiago Trujillo 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