【问题标题】:Using pick in array Nuxt 3 useFetch在数组 Nuxt 3 useFetch 中使用 pick
【发布时间】:2022-12-14 02:07:11
【问题描述】:

我正在尝试复制 nuxt 3 useFetch 样本,但到目前为止运气不好。 https://v3.nuxtjs.org/getting-started/data-fetching#usefetch

我的 post.vue 页面包含以下代码:

<template>
  <section>
    <div v-for="mountain in mountains" :key="mountain">{{mountain}}</div>
  </section>
</template>

<script setup>
  const runtimeConfig = useRuntimeConfig()

  const { data: mountains, pending, error, refresh } = await useFetch('/mountains',{
    baseURL: runtimeConfig.public.apiBase,
    pick: ['title']
  })
  
  console.log(mountains.value)
</script>

由于某种原因,数据未显示在模板中。 console.log()显示Proxy {title: undefined}

我已经意识到删除 pick 选项可以解决问题,所以我想知道 pick 是否只适用于对象而不能用于数组。 这很奇怪,因为示例使用的是数组 https://v3.nuxtjs.org/api/composables/use-fetch

【问题讨论】:

  • 如果你尝试{{ mountain.title }}会发生什么?另外,您在 Vue 开发工具中看到了什么?如果您想更轻松地检查它,使用 pre html 标记在 mountains 上也很有用。
  • 执行 {{ mountain.title }} 只会返回 Nuxt 错误 500,因为它未定义。显然 pick 只适用于对象,我不得不使用 transform 来解析数组。但我需要一些 Nuxt 大师来确认。我想对数组进行选择会将数组转换为具有未定义标题属性的单个对象
  • 我自己没用过(还)。我之前评论的第二部分怎么样,你试过第二部分了吗?
  • 正如您发现的那样,正如文档所说,pick 对结果起作用——而不是对结果数组的所有元素起作用。这可能是一个改进。
  • 可能可以通过对集合进行迭代来解决。我想我看到有人很容易做到这一点!

标签: vuejs3 server-side-rendering nuxtjs3


【解决方案1】:

pick 选项当前仅在您获取一个文档(一个 Js 对象)时才有效。

在官方文档中,您可以看到他们在 API 中获取特定文档:https://nuxt.com/docs/getting-started/data-fetching

您的一个选择是创建一个仅返回一个对象的 API 路由。

【讨论】:

    猜你喜欢
    • 2022-11-24
    • 2022-11-20
    • 2022-08-23
    • 2022-07-29
    • 2022-07-05
    • 2022-11-16
    • 2023-02-09
    • 2022-11-11
    • 2022-12-21
    相关资源
    最近更新 更多