使用Nuxt.js的async fetch()方法调用API获取数据时遇$get未定义错误
解决Nuxt.js async fetch()中“Cannot read properties of undefined (reading '$get')”错误
错误原因
- 未配置axios依赖:Nuxt.js默认不内置axios,
this.$http(或this.$axios)未被定义,导致无法调用$get方法。 - 变量赋值错误:fetch方法中直接写
posts = ...,未绑定组件实例的data属性,既无法更新页面数据,还可能产生全局变量污染。 - 组件标签误用:模板中使用了不存在的
<n-link>标签,需替换为Nuxt官方提供的<nuxt-link>。
修复步骤
1. 安装axios模块
执行终端命令安装依赖:
npm install @nuxtjs/axios
2. 在nuxt.config.js中配置axios
将axios添加到modules数组,可按需配置baseURL简化请求路径:
export default { modules: [ '@nuxtjs/axios', ], axios: { baseURL: 'https://jsonplaceholder.typicode.com' } }
3. 修正index.vue代码
- 替换
<n-link>为<nuxt-link> - 在fetch方法中使用
this.$axios调用接口,并正确赋值给组件的posts属性
修正后的完整代码:
<template> <div class="container"> <h1>Blog posts</h1> <p v-if="$fetchState.pending">Fetching posts...</p> <p v-else-if="$fetchState.error">Error while fetching posts: {{ $fetchState.error.message }}</p> <ul v-else> <li v-for="post of posts" :key="post.id"> <nuxt-link :to="`/posts/${post.id}`">{{ post.title }}</nuxt-link> </li> </ul> <nuxt-link to="about">about</nuxt-link> </div> </template> <script> export default { data() { return { posts: [], }; }, head() { return { title: "About the app", meta: [ { hid: "Description", name: "Description", content: "hello", }, ], }; }, async fetch() { this.posts = await this.$axios.$get('/posts'); console.log(this.posts); }, fetchOnServer: false, }; </script>
可选配置(使用$http别名)
如果习惯用this.$http调用接口,可在nuxt.config.js中添加别名配置:
axios: { alias: 'http' // 将$axios别名为$http }
配置后即可继续使用this.$http.$get()发起请求。
内容的提问来源于stack exchange,提问作者Lalit Joshi
相关产品推荐
相关产品推荐

