jsonapi
nuxt-jsonapi

轻松为 Nuxt 集成 JSON:API 客户端

Nuxt JSON:API logo

nuxt-jsonapi

npm version npm downloads Tests Codecov License

轻松为 Nuxt.js 集成 JSON:API 客户端

📖   发行说明

版本 2.x3.x 支持 Nuxt 3.x

版本 1.x 支持 Nuxt 2.x

介绍

nuxt-jsonapiNuxt 提供了轻松的 JSON:API 客户端集成。它是对优秀的 Kitsu JSON:API 客户端的松散封装。

此模块全局注入一个 $jsonApi 实例,您可以使用 this.$jsonApi (选项 API) 或 const { $jsonApi } = useNuxtApp() (组合式 API) 在任何地方访问该客户端。

设置

  1. nuxt-jsonapi 依赖添加到您的项目中
npm install nuxt-jsonapi
  1. nuxt-jsonapi 添加到 nuxt.config.jsmodules 部分
{
  modules: [
    // Simple usage
    'nuxt-jsonapi',

    // With options
    [
      'nuxt-jsonapi',
      {
        baseURL: 'http://www.example.com/api',
        /* other module options */
      },
    ],
  ]
}
  1. 如果您未在第 2 步传递选项,请在 nuxt.config.js 中添加一个 jsonApi 对象来配置模块选项
export default {
  modules: ['nuxt-jsonapi'],

  jsonApi: {
    baseURL: 'http://www.example.com/api',
    /* other module options */
  },
}

❗ 重要提示

如果您未指定 baseURL 选项,将使用默认的 /jsonapi URL。这几乎肯定不是您想要的,因此请务必正确设置。


使用

有关客户端提供的所有功能,请参阅 Kitsu 的优秀文档

您可以通过以下方式访问客户端

Options API

this.$jsonApi

示例

export default defineNuxtComponent({
  async asyncData({ $jsonApi }) {
    const { data } = await $jsonApi.get('/article')

    return {
      articles: data,
    }
  },
})

组合式 API

const { $jsonApi } = useNuxtApp()

示例

<script setup>
import { useNuxtApp, useAsyncData } from '#app'

const { $jsonApi } = useNuxtApp()

const { data: articles } = await useAsyncData(() => $jsonApi.get('/article'), {
  transform: ({ data }) => data,
})
</script>

开发

  1. 克隆此仓库
  2. 使用 yarn installnpm install 安装依赖项
  3. 使用 yarn devnpm run dev 启动开发服务器
  4. 使用 yarn testnpm run test 运行自动化测试
  • 运行 npm run dev:prepare 以生成类型存根。
  • 使用 npm run dev 在开发模式下启动 playground

许可证

麻省理工学院许可证

版权所有 (c) Patrick Cate