[英]How to use $axios Nuxt module inside of setup() from composition API?
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()
.文档说在methods/mounted/etc
内部使用this.$axios.$get()
,但是在setup()
内部调用时会抛出TypeError: _this is undefined
。 Is $axios
compatible with the composition API? $axios
是否与组合 API 兼容?
To clarify, I'm specifically talking about the axios nuxt plugin, not just using axios generically.为了澄清,我特意谈论的是 axios nuxt 插件,而不仅仅是一般地使用 axios。 https://axios.nuxtjs.org/ https://axios.nuxtjs.org/
So for instance, something like this throws the error above因此,例如,这样的事情会引发上面的错误
export default {
setup: () => {
const data = this.$axios.$get("/my-url");
}
}
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
好的,所以使用 Nuxt 插件 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然后您可以继续测试页面并运行此类代码以获得成功的 axios
<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...).在这种情况下,我不确定如何在全局范围内导入 axios,但由于它是 API 的组成部分,因此您不要使用选项 API 键(已mounted
等)。
Thanks to this post for the insight on how to use Vue3: https://stackoverflow.com/a/65015450/8816585感谢这篇文章了解如何使用 Vue3: https://stackoverflow.com/a/65015450/8816585
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.