After retrieving data from an API, I populate a form in my component. The challenge I am facing is that the watchers are triggered immediately after populating the initial data. I want them to be triggered asynchronously. Additionally, I need to prevent the Update button from being enabled if any value has changed after the initial data population.
<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 looked into resources like Vue, await for Watch, Are watches asynchronous?, and Vue.js How to watcher before mounted(), can't get data from watch, but I am struggling to implement their suggestions.
See the live example here: https://codesandbox.io/embed/great-euler-skd3v?fontsize=14&hidenavigation=1&theme=dark