Skip to content

Instantly share code, notes, and snippets.

@mccabiles
Last active May 26, 2019 03:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mccabiles/3e2b3ced0cf1517607123c00e90c70db to your computer and use it in GitHub Desktop.
Save mccabiles/3e2b3ced0cf1517607123c00e90c70db to your computer and use it in GitHub Desktop.
<script>
export default {
props: {
id: Number,
},
data() {
return {
avenger: {} // Our avenger object is initially empty
};
},
methods: {
async getData() {
// API calls are usually asynchronous:
const avenger = await this.$api.get(`avengers/${this.id}`);
this.avenger = avenger;
}
},
}
</script>
<script>
export default {
props: {
id: Number,
},
data() {
return {
avenger: {}
};
},
watch: {
id: {
immediate: true,
async handler(id) {
// We also replace 'this.id' simply with the 'id' argument:
const avenger = await this.$api.get(`avengers/${id}`);
this.avenger = avenger;
}
}
}
}
<script>
export default {
props: {
id: Number,
},
data() {
return {
avenger: {}
};
},
watch: {
id: {
// This tells our component to fire the handler ASAP:
immediate: true,
handler: 'getData'
}
},
/* We don't need the mounted hook anymore!
* mounted() {
* this.getData();
* },
*/
methods: {
async getData() {
const avenger = await this.$api.get(`avengers/${this.id}`);
this.avenger = avenger;
}
},
}
</script>
<script>
export default {
props: {
id: Number,
},
data() {
return {
avenger: {}
};
},
mounted() {
// We call the getData method when the component is mounted
this.getData();
},
methods: {
async getData() {
const avenger = await this.$api.get(`avengers/${this.id}`);
this.avenger = avenger;
}
},
}
</script>
<script>
export default {
props: {
id: Number,
},
data() {
return {
avenger: {}
};
},
watch: {
// Call 'getData' when 'id' prop changes
id: 'getData',
},
mounted() {
this.getData();
},
methods: {
async getData() {
const avenger = await this.$api.get(`avengers/${this.id}`);
this.avenger = avenger;
}
},
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment