Sometimes, we want to fix Axios can’t set data in Vue.js.
In this article, we’ll look at how to fix Axios can’t set data in Vue.js.
How to fix Axios can’t set data in Vue.js?
To fix Axios can’t set data in Vue.js, we should make sure methods and hook methods are all regular functions.
For instance, we write
<template>
<span>{{ data }}</span>
</template>
<script>
export default {
name: "MyComponent",
//...
async beforeMount() {
const { data } = await axios.get("http://127.0.0.1/api/bills");
this.data = data;
},
//...
};
</script>
to add the beforeMount
hook by setting the beforeMount
property to a regular function.
In it, we call axios.get
to make a GET request.
Then we get the response body from the data
property returned by the promise.
Finally, we set this.data
to data
so that we can use the data from the request elsewhere in the component.
this
should be referencing the current component instance since beforeMount
is set to a regular function.
Conclusion
To fix Axios can’t set data in Vue.js, we should make sure methods and hook methods are all regular functions.