【发布时间】:2025-04-13 22:35:02
【问题描述】:
代码 sn-ps 是用 Pug 和 Coffeescript 编写的
我知道 asyncData 及其局限性,但是从 Nuxt.js 中的组件获取异步数据的最佳做法是什么?
我在页面中写了一些逻辑,但显然不能接受,因为我有两张以上的卡片。
asyncData: ->
axios.defaults.baseURL = 'https://api.github.com/repos/username'
{ data: repo1 } = await axios '/repo1'
{ data: repo4 } = await axios '/repo4'
{ data: repo8 } = await axios '/repo8'
{ data: repo18 } = await axios '/repo18'
{
repo1:
stargazers: repo1.stargazers_count
description: repo1.description
url: repo1.html_url
repo4:
stargazers: repo4.stargazers_count
description: repo4.description
url: repo4.html_url
repo8:
stargazers: repo8.stargazers_count
description: repo8.description
url: repo8.html_url
repo18:
stargazers: repo18.stargazers_count
description: repo18.description
url: repo18.html_url
}
CardSlot(
title='repo1'
:subtitle='repo1.description'
:titleLink='repo1.url'
)
h1 {{repo1.stargazers}}
CardSlot(
title='repo4'
:subtitle='repo4.description'
:titleLink='repo4.url'
)
h1 {{repo4.stargazers}}
CardSlot(
title='repo8'
:subtitle='repo8.description'
:titleLink='repo8.url'
)
h1 {{repo8.stargazers}}
CardSlot(
title='repo18'
:subtitle='repo18.description'
:titleLink='repo18.url'
)
h1 {{repo18.stargazers}}
我只想写:
CardSlot(
title='repo1'
)
CardSlot(
title='repo4'
)
CardSlot(
title='repo8'
)
CardSlot(
title='repo18'
)
在 CardSlot 组件内部,所有的数据魔法都会发生
添加 #3:最后一击!
所以现在我需要的就是以某种方式将它传递给 props\slots
就asyncData而言
asyncData: ({ params }) ->
axios.defaults.baseURL = 'https://api.github.com/repos/username'
repo = 'repo22'
res = await axios('/' + repo)
{
stargazers: res.data.stargazers_count
description: res.data.description
url: res.data.html_url
}
...
h1 {{description}}
我想我需要定义一个数组,因此可以在循环中获取数据,在页面加载之前以及之后以某种方式将其传递给卡槽
【问题讨论】:
标签: asynchronous coffeescript fetch nuxt.js