最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 patible with the position API?

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

So for instance, something like this throws the error above

export default {
  setup: () => {
    const data = this.$axios.$get("/my-url");
  }
}

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 patible with the position API?

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

So for instance, something like this throws the error above

export default {
  setup: () => {
    const data = this.$axios.$get("/my-url");
  }
}
Share Improve this question edited May 5, 2021 at 5:47 Mrweiner asked May 4, 2021 at 23:47 MrweinerMrweiner 5211 gold badge8 silver badges24 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10
import { useContext } from '@nuxtjs/position-api';

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

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

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

Vue.use(VueCompositionApi)

nuxt.config.js

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

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/position-api'

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

I'm not sure about how to import axios globally in this case but since it's position 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./a/65015450/8816585

发布评论

评论列表(0)

  1. 暂无评论