How to use $axios Nuxt module inside of setup() from composition API?

Viewed 2346

The docs say to use this.$axios.$get() inside of methods/mounted/etc, but that throws TypeError: _this is undefined when called inside of setup(). Is $axios compatible with the composition API?

To clarify, I'm specifically talking about the axios nuxt plugin, not just using axios generically. https://axios.nuxtjs.org/

So for instance, something like this throws the error above

export default {
  setup: () => {
    const data = this.$axios.$get("/my-url");
  }
}
2 Answers
import { useContext } from '@nuxtjs/composition-api';

setup() {
  const { $axios } = useContext();
}

Alright, so with the usual configuration of a Nuxt plugin aka plugins/vue-composition.js

import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'

Vue.use(VueCompositionApi)

nuxt.config.js

plugins: ['~/plugins/vue-composition']

You can then proceed with a test page and run this kind of code to have a successful axios get

<script>
import axios from 'axios'
import { onMounted } from '@vue/composition-api'

export default {
  name: 'App',
  setup() {
    onMounted(async () => {
      const res = await axios.get('https://jsonplaceholder.typicode.com/posts/1')
      console.log(res)
    })
  },
}
</script>

I'm not sure about how to import axios globally in this case but since it's composition API, you do not use the options API keys (mounted etc...).

Thanks to this post for the insight on how to use Vue3: https://stackoverflow.com/a/65015450/8816585

Related