1👍
✅
You could do that using the Nuxt Composition-API’s useContext
. I’ve added a working simple code and link below.
To access Nuxt’s context using the composition API useContext
as explained on @nuxtjs/composition-api doc,
you need to import the useContext
.
e.g. import { useContext } from '@nuxtjs/composition-api'
This way you can access all Nuxt context and in this case, you can access $axios
module too.
import { ref, defineComponent, useContext } from "@nuxtjs/composition-api";
export default defineComponent({
setup() {
const todo = ref([]);
const fetching = ref(false);
const { $axios } = useContext();
const fetchPosts = async () => {
try {
fetching.value = true;
const response = await $axios.get(
"https://jsonplaceholder.typicode.com/todos/1"
);
todo.value = response.data;
} catch (error) {
// Handle the error here
console.error("Error fetching todo:", error);
} finally {
fetching.value = false;
}
};
return {
todo,
fetchPosts,
fetching,
};
},
});
<div>
<h1>TODOs</h1>
<button @click="fetchPosts">Fecth Tasks</button>
<p v-if="fetching">Fetching...</p>
<pre v-else>
{{ JSON.stringify(todo, null, 3) }}
</pre>
</div>
`
Here is the link to the codesandbox – https://codesandbox.io/s/nuxt-2-composition-api-and-axios-integration-pmzxq8
Source:stackexchange.com