You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Nuxt.js的async fetch()方法调用API获取数据时遇$get未定义错误

解决Nuxt.js async fetch()中“Cannot read properties of undefined (reading '$get')”错误

错误原因

  1. 未配置axios依赖:Nuxt.js默认不内置axios,this.$http(或this.$axios)未被定义,导致无法调用$get方法。
  2. 变量赋值错误:fetch方法中直接写posts = ...,未绑定组件实例的data属性,既无法更新页面数据,还可能产生全局变量污染。
  3. 组件标签误用:模板中使用了不存在的<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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:20:27