Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
How to watch only after the initial load from API in VueJS?

I am getting data from API with which I am populating the form in my component. I need to trigger watchers only after the initial populating of data. Like in async way. But the watcher is getting triggered immediately. I need to disable the Update button only if any value is changed after the initial populating of data.

<template>
  <div id="app">
    <input type="text" v-model="user.userId" /> <br />
    <br />
    <input type="text" v-model="user.title" /> <br />
    <br />
    <button :disabled="isDisabled">Update</button>
  </div>
</template>

<script>
export default {
  name: "App",
  watch: {
    user: {
      handler(oldVal, newVal) {
        if (oldVal != newVal) {
          this.isLoaded = false;
        }
      },
      deep: true,
    },
  },
  computed: {
    isDisabled() {
      return this.isLoaded;
    },
  },
  async created() {
    await fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => {
        this.user = json;
        this.isLoaded = true;
      });
  },
  data() {
    return {
      user: {
        userId: 0,
        id: 0,
        title: "",
        completed: false,
      },
      isLoaded: true,
    };
  },
};
</script>

I have referred Vue, await for Watch and Are watches asynchronous? and Vue.js How to watcher before mounted() , can't get data from watch but I am unable to follow.

Here's a preview : https://codesandbox.io/embed/great-euler-skd3v?fontsize=14&hidenavigation=1&theme=dark

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This needs to be determined with some condition.

isLoaded already serves the purpose of determining the state of initial loading, but the name is confusing, because it determines that data is not loaded.

It can be:

  watch: {
    user: {
      if (this.isLoading && oldVal != newVal) {
        this.isLoading = false;
      }
      ...

The watcher doesn't need to be deep and could be unwatched when it's not needed:

async created() {
  let unwatchUser = this.$watch('user', (oldVal, newVal) => {
    if (this.isLoading && oldVal != newVal) {
      this.isLoading = false;
      unwatchUser();
    }
  })
  ...

A common way to designate that data hasn't been loaded yet is to set it to null, i.e. no value. This doesn't need isLoading flag or a watcher. If null is undesirable because of referred object properties, this can be overcome with optional chaining and conditional rendering:

  <div v-if="user">
      <input type="text" v-model="user.userId" />
      ...
  <div v-else class="spinner"/>
about 4 years ago · Juan Pablo Isaza Denunciar

0

The simplest answer for the question:

Q: How to watch only after the initial load from API in VueJS?

A: Add flag inside your watch (e.g. isLoaded).

Also there is couple things wrong with your code:

  • async/await in created does nothing,
  • isDisabled is not needed cause is basing only on 1 value from data. You can just use this value instead (isLoading).
  • If you api calls fail, isLoading flag will not change, better approach is to move it to finally.

Solution of your problem (codesandbox) :

<template>
  <div id="app">
    <div v-if="!isFetching">
      <input type="text" v-model="user.userId" /> <br />
      <br />
      <input type="text" v-model="user.title" /> <br />
      <br />
      <button :disabled="!isLoaded">Update</button>
    </div>
    <div v-else>Loading...</div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      user: {
        userId: 0,
        id: 0,
        title: "",
        completed: false,
      },
      isFetching: false,
      isLoaded: false
    };
  },
  watch: {
    user: {
      handler(oldVal, newVal) {
        if (!this.isFetching) {
          // this comparision doesn't work (cause oldVal/newVal is an object)
          if (oldVal != newVal) {
            this.isLoaded = false;
          }
        }
      },
      deep: true
    },
  },
  created() {
    this.isFetching = true;
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => {
        this.user = json;
        this.isLoaded = true;
      })
      .finally(() => this.isFetching = false)
  },
};
</script>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda