为什么我不能渲染ajax json值?

发布于 2025-02-07 12:32:36 字数 926 浏览 0 评论 0原文

这是我的代码:

<ul>
  <li v-for="value in RandomTopic" :key="value.id">{{ value.title }}</li>
</ul>
export default {
  data() {
    return {
      RandomTopic: null
    }
  },
  mounted() {
     ///some method to get data from remote server
     console.log(res.data);
     this.RandomTopic = res.data;
  }
}

我想从前端渲染远程服务器的所有数据。但是,在程序运行后,它报告了此错误:

Cannot set property 'RandomTopic' of undefined ; at api request success callback function
TypeError: Cannot set property 'RandomTopic' of undefined

console.log(res.data);记录json,因此似乎不是AJAX或远程问题服务器。

而且,这是JSON的示例:

[
    {
        "id": 421,
        "title": "sample1",
        "image_url": "bus.png"
    },
    {
        "id": 535,
        "title": "sample78",
        "image_url": "car.png"
    }
]

我的代码怎么了?我是Vue 3的初学者,请帮助我。

Here is my code:

<ul>
  <li v-for="value in RandomTopic" :key="value.id">{{ value.title }}</li>
</ul>
export default {
  data() {
    return {
      RandomTopic: null
    }
  },
  mounted() {
     ///some method to get data from remote server
     console.log(res.data);
     this.RandomTopic = res.data;
  }
}

I want to render all the data from the remote server in front end. However, after the program ran, it reports this error:

Cannot set property 'RandomTopic' of undefined ; at api request success callback function
TypeError: Cannot set property 'RandomTopic' of undefined

The console.log(res.data); log the JSON successfully so it seems not the problem of AJAX or remote server.

And also, here is a sample of the JSON:

[
    {
        "id": 421,
        "title": "sample1",
        "image_url": "bus.png"
    },
    {
        "id": 535,
        "title": "sample78",
        "image_url": "car.png"
    }
]

What's wrong with my code ? I am a beginner of Vue 3, please help me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千仐 2025-02-14 12:32:36

根据您提到的错误,问题基本上与的范围有关。看来您使用的是常规函数,而不是箭头函数(=&gt; {...})不提供自己的绑定(它保留了封闭词汇上下文的此值)。

参考 -

.then(res => {
    this.RandomTopic = res.data;
})

As per the error you mentioned, Issue is basically related to the scope of this. Looks like you are using regular function instead of arrow function ( => {...}) which don't provide their own this binding (it retains this value of the enclosing lexical context).

Reference - Arrow function

.then(res => {
    this.RandomTopic = res.data;
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文